Perl on Linux – Anonymous Hashes, Hash References, and Passing Them to Subroutines.

There comes a time in every perl programmers life when they have to master the hash. Anyone who has programmed in Perl for very long has run into problems such as subroutine arguments getting confusing, lagging programs due to hash tables being copied over and over, and searched for a simpler way to maintain and access data. All this and more can be achieved by the simple use of anonymous hash tables and the passing of hash table references to subroutines for processing.

An anonymous hash is one that doesn’t have a specific name, really, just a reference. They are declared like so:

my $myhash = { "key1" => "value1", "key2 => "value2", ... };

The variable defined here is a scalar, meaning it’s a number, more or less. What it does is holds the memory location for the start of the hash, so it tells us where the hash is. There are several ways to access the hash by using the reference to it:

%{$myhash}; # access the entire hash
${$myhash}{'key1'}; # one way to access the value of the 'key1' key.
$myhash->{'key1'}; # a better way to access the value of the 'key1' key.

The second and third examples are identical, just different syntax. And very useful. You can pass hash references to subroutines, making it easier to remember passed parameters.

my $myhash = { "key1" => "value1", "key2 => "value2"};
mySub($myhash);
sub mySub
{
  my $hashref = shift;
  $hashref->{'key1'}; # access to value1
}

This not only handy for passing in a lot of parameters easily and in an organized manner, but it is also more efficient and faster since the program just sends a small scalar pointing to the hash table rather than passing the whole hash table itself.

I hope this helps you out as it helped me out when I was getting into perl.

One thought on “Perl on Linux – Anonymous Hashes, Hash References, and Passing Them to Subroutines.

Leave a Reply