Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Default subroutine parameters

by stephen (Priest)
on Apr 22, 2002 at 18:52 UTC ( [id://161126]=note: print w/replies, xml ) Need Help??


in reply to Default subroutine parameters

The "defined" method is the best way, but there's a way to have your cake and eat it too, for a price... just define a sub that processes your arguments, filling in as necessary. Like so:

## ## _fd() ## ## Arguments: ## ARGUMENTS: arrayref -- The arguments to a subroutine ## DEFAULTS: arrayref -- The defaults for those arguments ## ## Returns: ## list -- The elements of ARGUMENTS. Any elements in ARGUMENTS ar +e replaced ## by the corresponding element in DEFAULTS. ## sub _fd { my ($args, $defaults) = @_; my @filled = (); foreach (0 .. max($#$args, $#$defaults)) { push @filled, ( defined( $args->[$_] ) ? $args->[$_] : $defaults-> +[$_] ); } return @filled; } sub max { ($_[0] > $_[1]) ? $_[0] : $_[1]; }
Then, in the rest of your code, you can just run your subroutines through _fd(), like so:
## ## test_default() ## ## Arguments: ## $name: string -- Somebody's name. (Optional) ## ## Prints "Hello my name is $name". Name defaults to "ben". ## sub test_default { my ($name) = _fd(\@_, ["ben"]); print "Hello my name is $name\n"; }

Then, test_default('luke') prints "Hello my name is luke", while test_default() prints "Hello my name is ben". There's some overhead to calling subroutines and doing list processing all the time, but you can use it most of the time.

Update: After thinking about this for a while, I figured out a way to use theDamian's Attribute::Handlers and a small amount of symbol-table work to give Perl a default attribute: Attribute::Default.

use base 'Attribute::Default'; sub test_default : default('ben') { my ($name) = @_; print "Hello my name is $name\n"; }

stephen

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2024-03-29 00:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found