Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

How do I reverse array elements?

by Anonymous Monk
on Nov 12, 2000 at 13:05 UTC ( [id://41167]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

How do I reverse array elements?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I reverse array elements?
by sdaniels (Initiate) on Feb 01, 2001 at 00:03 UTC
    @array2 = reverse( @array1 );

    Originally posted as a Categorized Answer.

Re: How do I reverse array elements?
by Fastolfe (Vicar) on Nov 12, 2000 at 13:24 UTC
Re: How do I reverse array elements?
by Nilotpal_1984 (Initiate) on Sep 01, 2015 at 12:03 UTC
    If you don't want to change the content of original array, you can use this: map {unshift(@reversed,$_)} @original;
Re: How do I reverse array elements?
by gridlock (Novice) on Feb 22, 2004 at 06:56 UTC
    Use the 'reverse' operator - - - one of the beauties of Perl - - -

    Originally posted as a Categorized Answer.

Re: How do I reverse array elements?
by superfrink (Curate) on Mar 11, 2006 at 05:17 UTC

    Of course, most of the time, reverse is adequate and correct; but the following gives you more control when you need it.

    sub rev { my @r; push @r, pop @_ while @_; @r }

Re: How do I reverse array elements?
by Anonymous Monk on Dec 18, 2003 at 01:16 UTC
    $i = 0; @arr = (1,2,3,4); $mid = $#arr/2; while ($i <= mid) { $tmp = $arr[$i]; $rear = $#arr-$i; $arr[$i] = $arr[$rear]; $arr[$rear] = $tmp; ++$i; }

    Originally posted as a Categorized Answer.

Re: How do I reverse array elements?
by simmisam (Novice) on Jan 15, 2014 at 22:19 UTC
    my @array1 = qw(4 3 7 8 9 49 12 23 43); my @array2; for (0..$#array1) { my $popElement = pop @array1; push (@array2,$popElement); } print "@array2\n";
Re: How do I reverse array elements?
by rajib (Novice) on Aug 20, 2002 at 18:03 UTC

    The following reverses an array in place, in case that's what you want:

    sub reverse_inplace { for ( my $i = 0; $i < $#_ / 2; $i++ ) { my $j = $#_ - $i; @_[$i,$j] = @_[$j,$i]; # swap } } # try it: my @a = ( 1 .. 9 ); reverse_inplace( @a ); print "@a\n";

    Originally posted as a Categorized Answer.

A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

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

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

    No recent polls found