Looping through key/value pairs from a Perl scalar hash reference

September 13, 2011 - 1 minute read -
perl looping key value pairs hash reference scalar

If you’ve got a hash ( %hash ), it’s easy enough to loop through all the key/value pairs with the following:

foreach my $key ( keys %hash )
{
print "key: $key, value: $hash{$key}\n";
}

We could reference the hash with:

 $href = \%hash; 

As the hash element is scalar, the $ notation is used.

To access the key/value pairs in a hash reference, the syntax differs slightly from the first example.

foreach my $key ( keys %{ $href } )
{
print "key: $key, value: ${$href}{$key}\n";
}

Perlreftut contains a more in depth explanation of Perl references.