code-tutorial.com

The best resources for developers

What's the safest way to iterate through the keys of Perl hash if you are an expert Perl developer?

foreach my $key (keys %hash) { ... }
foreach my $val (values %hash) { ... }
keys %hash; # reset the internal iterator so a prior each() doesn"t affect the loop
while(my($k, $v) = each %hash) { ... }
%h = (a => 1, b => 2);

foreach my $k (keys %h)
{
  $h{uc $k} = $h{$k} * 2;
}
(a => 1, A => 2, b => 2, B => 4)
%h = (a => 1, b => 2);

keys %h;
while(my($k, $v) = each %h)
{
  $h{uc $k} = $h{$k} * 2; # BAD IDEA!
}
(a => 1, A => 2, b => 2, B => 8)
keys %h;
while(my($k, $v) = each %h)
{
  if(...)
  {
    delete $h{$k}; # This is safe
  }
}
% perldoc -f keys
% perldoc -f each

Tags: iteration perl hash each

Source: By Rudd Zwolinski as answer to the question

This code snippet was collected from stackoverflow, and is licensed under CC BY-SA 2.5


Related code-snippets: