http://www.perlmonks.org?node_id=646327


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 (Archbishop) 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:  <%-{-{-{-<