How To Pass Hashes As Subroutine Arguments In Perl

Published Date Author: , Posted August 19th, 2011 at 1:17:09pm

A small step forwards in understanding how Perl handles hashes as arguments.

This biggest difference is that the first way “slurps” in ALL passed values in @_ into the %args hash. The second (cooler) way, pulls in the arguments hash as a single scalar variable, allowing multiple variables to be passed via @_, if you wanted to…

Compare this:

my $result = &mySub( 'key'=>'value' );

my %args = @_ || ();

my $value = $args{'key'} || '';

versus this:

my $result = &mySub({ 'key'=>'sampleValue' }, 'another value');

my $args = shift || {};

my $value = $args->{'key'} || ''; # gets 'sampleValue'

my $secondVal = shift || ''; # gets 'another value'

No comments as yet.

Leave Your Comment  Leave a comment

All fields marked with "*" are required.