Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Passing hashes as arguments to a sub?

by jimbojones (Friar)
on Nov 28, 2005 at 21:30 UTC ( [id://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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (8)
As of 2024-04-19 08:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found