looping-over-perl-hash

A lot of the time, you'll see people loop across keys in a hash like this:

foreach my $key (keys %hash) {
  print "$key => " . $hash{$value} . "\n";
}

Which is not very efficient especially if %hash is very large because the "keys" call constructs a large array.

Looping across all key/value pairs in a hash is best accomplished by using a while loop:

while (my ($key, $value) = each(%hash)) {
  print "$key => $value\n";
}

Notes:

  • The each function, when called in list context, returns a 2-element list containing the key and value of the next element of the hash.
  • When the hash is entirely read, a null array is returned in list context. Assignment of a null array produces an undef in scalar context, ending the while.
  • The ordering of the keys by each is undefined.
  • You can't modify the %hash while "each-ing" over it.

Follow on Twitter


LinkedIn
Facebook
Notchup, Member 74311




Copyright (C) 2008, Mike McCreavy
[ x ] Console
Timestamp Message
hey
[ x ] Socket Console
Timestamp Message
hey