What are anonymous hashes in perl?

user1363308 picture user1363308 · Jan 5, 2013 · Viewed 20.8k times · Source
$hash = { 'Man' => 'Bill',
          'Woman' => 'Mary,
          'Dog' => 'Ben'
        };

What exactly do Perl's “anonymous hashes” do?

Answer

TLP picture TLP · Jan 5, 2013

It is a reference to a hash that can be stored in a scalar variable. It is exactly like a regular hash, except that the curly brackets {...} creates a reference to a hash.

Note the usage of different parentheses in these examples:

%hash = ( foo => "bar" );   # regular hash
$hash = { foo => "bar" };   # reference to anonymous (unnamed) hash
$href = \%hash;             # reference to named hash %hash

This is useful to be able to do, if you for example want to pass a hash as an argument to a subroutine:

foo(\%hash, $arg1, $arg2);

sub foo {
    my ($hash, @args) = @_;
    ...
}

And it is a way to create a multilevel hash:

my %hash = ( foo => { bar => "baz" } );  # $hash{foo}{bar} is now "baz"