Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Passing hashes as arguments to a sub?

by jimbojones (Friar)
on Nov 28, 2005 at 21:30 UTC ( #512385=note: print w/ replies, xml ) Need Help??


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


Comment on Re: Passing hashes as arguments to a sub?
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://512385]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (7)
As of 2014-08-31 04:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (294 votes), past polls