Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Printing an array using while loop

by perlfan (Priest)
on Oct 21, 2007 at 22:52 UTC ( #646327=note: print w/replies, xml ) Need Help??


in reply to Printing an array using while loop

or:
my @array1 = qw/ball bat helmet/; while (@array1) { my $item = pop @array1; print $item; push(@array2,$item); }
That is if you care about keeping the original contents - otherwise:
my @array1 = qw/ball bat helmet/; while (@array1) { print pop @array1; }

Replies are listed 'Best First'.
Re^2: Printing an array using while loop
by AnomalousMonk (Bishop) on May 19, 2020 at 23:18 UTC

    If order is important, pop is wrong in both examples:

    c:\@Work\Perl\monks>perl -wMstrict -le "my @array1 = qw/ball bat helmet/; print qq{\@array1 before: (@array1)}; ;; my @array2; while (@array1) { my $item = pop @array1; print $item; push(@array2,$item); } print qq{\@array2 after: (@array2)}; " @array1 before: (ball bat helmet) helmet bat ball @array2 after: (helmet bat ball)
    shift does the trick:
    c:\@Work\Perl\monks>perl -wMstrict -e "use Data::Dump qw(dd); ;; my @array1 = (qw/ball bat helmet/, 0, undef); dd '@array1 before:', \@array1; ;; my @array2; while (@array1) { my $item = shift @array1; dd $item; push(@array2,$item); } dd '@array2 after:', \@array2; " ("\@array1 before:", ["ball", "bat", "helmet", 0, undef]) "ball" "bat" "helmet" 0 undef ("\@array2 after:", ["ball", "bat", "helmet", 0, undef])


    Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2020-10-01 05:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If at first I donít succeed, I Ö










    Results (174 votes). Check out past polls.

    Notices?