Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

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?

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 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?

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2022-01-20 06:19 GMT
Find Nodes?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:

    Results (56 votes). Check out past polls.