in reply to Re^2: Different result for 'foreach' vs 'while shift' arrayref
in thread Different result for 'foreach' vs 'while shift' arrayref
That's certainly true. I often use that, and have no idea why I didn't suggest it myself!
Generally speaking the reason to use this idiom is when you need to loop through a list and in each iteration you need to take one or more items from the list.This kind of thing:
use strict; use warnings; use Data::Dumper; my @input = ( 'foo:' => 1, 'bar:' => 2, 'baz', # no colon, so value is "1" 'quux:' => 3, ); my %output; while (@input) { my $key = shift @input; if ($key =~ /\A(.+):\z/) { $output{$1} = shift @input; } else { $output{$key} = 1; } } print Dumper \%output;
If you only need to step through the list one at a time, use foreach; it's clearer.
|
---|