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
Leave a Reply