How To Pass Hashes As Subroutine Arguments In Perl
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'
Leave Your Comment
All fields marked with "*" are required.