Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are anonymous hashes in perl?

$hash = { 'Man' => 'Bill',
          'Woman' => 'Mary,
          'Dog' => 'Ben'
        };

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

like image 828
user1363308 Avatar asked Jan 05 '13 19:01

user1363308


People also ask

What is anonymous array in Perl?

Array references—which anonymous arrays are one type of—allows Perl to treat the array as a single item. This allows you to build complex, nested data structures as well. This applies to hash, code, and all the other reference types too, but here I'll show only the hash reference.

How do I check if a Perl hash is empty?

From perldoc perldata: If you evaluate a hash in scalar context, it returns false if the hash is empty. If there are any key/value pairs, it returns true; more precisely, the value returned is a string consisting of the number of used buckets and the number of allocated buckets, separated by a slash.

How do I create a hash reference in Perl?

Similar to the array, Perl hash can also be referenced by placing the '\' character in front of the hash. The general form of referencing a hash is shown below. %author = ( 'name' => "Harsha", 'designation' => "Manager" ); $hash_ref = \%author; This can be de-referenced to access the values as shown below.


1 Answers

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"
like image 152
TLP Avatar answered Sep 19 '22 15:09

TLP