Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

Re: Default subroutine parameters

by stephen (Priest)
on Apr 22, 2002 at 18:52 UTC ( #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"; }


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://161126]
[ambrus]: You can actually get a lot of useful cheap really almost new products that way, with only a little risk of scams.
[ambrus]: That's what some of the "Black Friday" sales are about.
[Corion]: ambrus: Well, usually, these people don't have in their description "mail me at dodgy_reseller # g m a i l | co m" , replace the "#" by "@" :)
[Corion]: Oh, and the "o" in "com" is a zero
choroba orders a camera from Ole Scæmmer
[ambrus]: Corion: ah. that's different. the ones I mean are selling at reputable sites like ebay that usually filters scammers out pretty quickly (as well as filters a lot of legitimate users who then get annoyed that the biggest providers exclude them)

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (13)
As of 2017-11-21 15:04 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (304 votes). Check out past polls.