start page | rating of books | rating of authors | reviews | copyrights

Perl Cookbook

Perl CookbookSearch this book
Previous: 11.2. Making Hashes of Arrays Chapter 11
References and Records
Next: 11.4. Taking References to Functions
 

11.3. Taking References to Hashes

Problem

You need to manipulate a hash by reference. This might be because it was passed into a function that way or because it's part of a larger data structure.

Solution

To get a hash reference:

$href = \%hash; $anon_hash = { "key1" => "value1", "key2" => "value2", ... }; $anon_hash_copy = { %hash };

To dereference a hash reference:

%hash  = %$href; $value = $href->{$key}; @slice = @$href{$key1, $key2, $key3};  # note: no arrow! @keys  = keys %$href;

To check whether something is a hash reference:

if (ref($someref) ne 'HASH') {     die "Expected a hash reference, not $someref\n"; }

Discussion

This example prints out all the keys and values in two predefined hashes:

foreach $href ( \%ENV, \%INC ) {       # OR: for $href ( \(%ENV,%INC) ) {     foreach $key ( keys %$href ) {         print "$key => $href->{$key}\n";     } }

Accessing slices of hashes by reference works just as it does with slices of arrays by reference. For example:

@values = @$hash_ref{"key1", "key2", "key3"};  for $val (@$hash_ref{"key1", "key2", "key3"}) {     $val += 7;   # add 7 to each value in hash slice } 

See Also

Recipe 5.0 ; Chapter 4 of Programming Perl ; perlref (1); Recipe 11.9


Previous: 11.2. Making Hashes of Arrays Perl Cookbook Next: 11.4. Taking References to Functions
11.2. Making Hashes of Arrays Book Index 11.4. Taking References to Functions