Nano's Blog

01/06/2010

The each Function

Filed under: programming — Tags: — nano @ 09:09

If you wish to iterate over (that is, examine every element of) an entire hash, one of the usual ways is to use the each function, which returns a key-value pair as two-element list.

#!C:\Perl\bin\perl.exe
use strict;
use warnings;

# declare a new hash
my %some_hash;

%some_hash = ("foo", 35, "bar", 12.4, 2.5, "hello",
      "wilma", 1.72e30, "betty", "bye");

my $key;
my $value;

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

print "\n";
foreach $key (sort keys %some_hash) {
  $value = $some_hash{$key};
  print "$key => $value\n";
  # Or, we could have avoided the extra $value variable:
  #  print "$key => $hash{$key}\n";
}

Output

betty => bye
bar => 12.4
wilma => 1.72e+030
foo => 35
2.5 => hello

2.5 => hello
bar => 12.4
betty => bye
foo => 35
wilma => 1.72e+030

-from Learning Perl 5E

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress