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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.