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.
TheDamian's new book, Perl Best Practices, covers this in Chapter 9. He recommends passing a hash reference, typically to an anonymous hash.
The reasons given for not passing a list of raw key/value pairs is: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; }
Requiring the named arguments to be specified inside a hash ensures that any mismatch, such as: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.will be reported (usually at compile time) in the caller’s context:$line = padded({text=>$line, cols=>20..21, centered=>1, filler=>$SPACE +});Passing those arguments as raw pairs:Odd number of elements in anonymous hash at demo.pl line 42would 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:$line = padded(text=>$line, cols=>20..21, centered=>1, filler=>$SPACE) +;
- j
|
---|
In Section
Seekers of Perl Wisdom