Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Print every past three months from current month

by wazat (Monk)
on Apr 01, 2014 at 03:23 UTC ( [id://1080475]=note: print w/replies, xml ) Need Help??


in reply to Print every past three months from current month

Why not take a slice instead of using splice.

my @a = qw( a b c d e f g ); sub f { my $i = shift; print join(',', @a[$i-2, $i-1, $i]), "\n"; } f(0); f(1); f(2); f(6);

outputs

f,g,a g,a,b a,b,c e,f,g

Replies are listed 'Best First'.
Re^2: Print every past three months from current month
by Anonymous Monk on Apr 01, 2014 at 13:00 UTC
    Hi, think if it was months, the count has to go backwards, and I can't get it to do it:
    my @months = qw( January February March April May June July October No +vember December ); # passing 4 for April, I should get "February March April", instead I +get: "March April May". f(4); sub f { my $i = shift; print join(',', @months[$i-2, $i-1, $i]), "\n"; }

    Thanks!

      Remember that perl array indices start at zero. April would have index 3, not 4. Also you are missing August and September.

      my @months = qw( January February March April May June July August Sep +tember October November December ); f(3); # Apr f(0); # Jan f(11); # Dec sub f { my $i = shift; print join(',', @months[$i-2, $i-1, $i]), "\n"; }

      Output

      February,March,April November,December,January October,November,December
      c:\@Work\Perl\monks>perl -wMstrict -le "my %months_name = qw( 1 January 2 February 3 March 4 April 5 May 6 June 7 July 8 August 9 September 10 October 11 November 12 December ); ;; my @months = map $months_name{$_}, sort { $a <=> $b } keys %months_na +me; ;; for my $n (1 .. 12) { my @prev_3 = map $n-1+$_, -3 .. -1; @prev_3 = @months[ @prev_3 ]; print qq{(@prev_3) before $months_name{$n} (month $n)}; } " (October November December) before January (month 1) (November December January) before February (month 2) (December January February) before March (month 3) (January February March) before April (month 4) (February March April) before May (month 5) (March April May) before June (month 6) (April May June) before July (month 7) (May June July) before August (month 8) (June July August) before September (month 9) (July August September) before October (month 10) (August September October) before November (month 11) (September October November) before December (month 12)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1080475]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (3)
As of 2024-04-20 01:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found