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


In reply to Re: Default subroutine parameters by stephen
in thread Default subroutine parameters by thelenm

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.