Anonymous Perl Hashes

If your passing variables to a subroutine in perl, using Perl Hashes and Anonymous Perl Hashes to send a list of configuration options is a handy way to save a few lines of code.

Anonymous hashes are hashes just like any other but you can declare them anywhere. They can come in handy when you need to send some other data besides what you would normally reference in your hash.

For example lets say you have a hash with the following entries in it “Name => John, LastName => Doe, Age => 21” and you wanted a way to send this to a subroutine over and over again, so you reference it with a hash. But you need to send it something different in just one line. Like changing the Age in your hash data.

Instead of sending your sub routine the fully populated hash as you normally would, like this:


#!/usr/bin/perl

use strict;
use warnings;

my $info = ({‘Name’ => “John”, ‘LastName’ => “Doe”, ‘Age’ => “21”});

printInfo($info);

sub printInfo {

my $info = shift;

print “Firstname: $info->{‘Name’}\n”;
print “Lastname : $info->{‘LastName’}\n”;
print “Age : $info->{‘Age’}\n”;

}

You can simply do something like this:


#!/usr/bin/perl

use strict;
use warnings;

printInfo({‘Name’ => “John”, ‘LastName’ => “Doe”, ‘Age’ => “27”});

sub printInfo {

my $info = shift;

print “Firstname: $info->{‘Name’}\n”;
print “Lastname : $info->{‘LastName’}\n”;
print “Age : $info->{‘Age’}\n”;

}

Anonymous Hashes are a simple and flexible way to send a modified hash reference to a sub routine in perl. Hopefully you found this scripting tutorial helpful. If you have any questions or suggestions be sure to leave a comment.

-Tutor


Posted

in

by

Tags:

Comments

One response to “Anonymous Perl Hashes”

  1. […] additional reading on hashes be sure to check out our previous article on using Anonymous Perl Hashes.  You can also read more over at perl.org’s perldoc […]

Leave a Reply

Your email address will not be published. Required fields are marked *