each() on arrays
With the fairly new Perl 5.12, each() now accepts an array, as opposed to only a hash.
each returns a 2 element list, containing the key and value for the next element in a hash, and now, in an array as well. In addition to the usual:
my %hash = (
foo => 12,
bar => 42,
);
while( my($key, $value) = each(%hash) ) {
print "$key => $value\n";
}
we can also do this:
my @array = ('a' .. 'z');
while( my($index, $element) = each(@array) ) {
print "$index: $element\n";
}
The index is the key, and the element itself is the value. This means we can do things like:
while( my($i, $e) = each(@array)) {
print "\$array[$i] = $e\n" if $e eq 'm';
}
instead of manually keeping count:
my $i = 0;
for my $e(@array) {
if($e eq 'm') {
print "\$array[$i] = $e\n";
}
$i++;
}