Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: For Loops and Reversing output

by liverpole (Monsignor)
on Dec 12, 2006 at 00:42 UTC ( #589201=note: print w/ replies, xml ) Need Help??


in reply to For Loops and Reversing output

Hi brusimm,

There are a lot of ways to use an array backwards.

One is to simply reverse the order of the sort.  For example, instead of

my @sorted = sort @unsorted;

which is doing an implicit sort { $a cmp $b } @unsorted, you could do:

my @sorted = sort { $b cmp $a } @unsorted;

to have the order reversed at the end of the sort.

Another way is to read an item one-at-a-time from the end of the list, such as in:

my $nextitem; while ($nextitem = pop @rocks) { # Use $nextitem }

(Sorry, I couldn't resist using pop @rocks :-))

As a 3rd and final example, read one at a time from the end of the array using an index, using the -N notation (which reads from the -Nth value of the array each time):

for (my $i=1; $i <= @rocks; $i++) { my $nextitem = $rocks[- $i]; # Take the ${i}th item from the en +d }

s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/


Comment on Re: For Loops and Reversing output
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (12)
As of 2014-09-23 19:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (240 votes), past polls