Wednesday, April 28, 2010

Itrating Hashes in Perl: Many ways

1) If you just want the keys and do not plan to ever read any of the values, use keys():

foreach my $key (keys %hash) { ... }

2) If you just want the values, use values():

foreach my $val (values %hash) { ... }

3) If you need the keys and the values, use each():

keys %hash; # reset the internal iterator so a prior each() doesn't affect the loop
while(my($k, $v) = each %hash) { ... }

4) If you plan to change the keys of the hash in any way except for deleting the current key during the iteration, then you must not use each(). For example, this code to create a new set of uppercase keys with doubled values works fine using keys():

%h = (a => 1, b => 2);

foreach my $k (keys %h)
{
$h{uc $k} = $h{$k} * 2;
}

No comments: