http://www.perlmonks.org?node_id=512385


in reply to Passing hashes as arguments to a sub?

Hi
TheDamian's new book, Perl Best Practices, covers this in Chapter 9. He recommends passing a hash reference, typically to an anonymous hash.

my $foo = CalcFoo( { bar => 'abc', baz => 'def' } ); sub CalcFoo { my $href = $_[0]; my $foo; if ( defined $href->{bar} and defined $href->{baz} ) { $foo = $href->{bar} . $href->{baz}; } else { print "Error: pls define bar and baz\n"; } return $foo; }
The reasons given for not passing a list of raw key/value pairs is:
Requiring the named arguments to be specified inside a hash ensures that any mismatch, such as:
$line = padded({text=>$line, cols=>20..21, centered=>1, filler=>$SPACE +});
will be reported (usually at compile time) in the caller’s context:
Odd number of elements in anonymous hash at demo.pl line 42
Passing those arguments as raw pairs:
$line = padded(text=>$line, cols=>20..21, centered=>1, filler=>$SPACE) +;
would cause the exception to be thrown at run time, and from the line inside the subroutine where the odd number of arguments were unpacked and assigned to a hash:
The chapter on subroutines is currently available as a sample chapter on the O'Reilly website for you to peruse. It's a great book, highly recommended.

- j