in reply to Default subroutine parameters

or with hashes.
&foo (bar=>"1"); sub foo { %args=@_; %defaults=(foo=>9, bar=>8, baz=>7); foreach ("foo", "bar", "baz") { defined ($args{$_}) || {$args{$_}= $defaults{$_}} ; print $args {$_} } }


update : or better yet, with the keys that you expect the sub to know :
&foo (bar=>"1"); sub foo { %args=@_; %defaults=(foo=>9, bar=>8, baz=>7); foreach (keys %defaults) { defined ($args{$_}) || {$args{$_}= $defaults{$_}} ; print $_ ," - ",$args {$_},"\n"; } }
update : or better yet, just like Fletch sez. Nice stuff.

Replies are listed 'Best First'.
Re: Re: Default subroutine parameters (boo)
by Fletch (Bishop) on Apr 22, 2002 at 16:59 UTC
    sub foo { my %defaults = ( qw( foo 9 bar 8 baz 7 ) ); my %args = ( %defaults, @_ ); ... }
      I really like this solution because it's syntactically simple. It works when an argument is omitted entirely, but unfortunately it doesn't supply the default value when the value 'undef' is passed as an argument, like this:
      mysub(foo => 0, bar => 1, baz => undef); sub mysub { my %defaults = qw(foo 9 bar 8 baz 7); my %args = (%defaults, @_); print "Foo: $args{foo}, Bar: $args{bar}, Baz: $args{baz}\n"; }

      But it's inspired me to see if I can modify it to suit my needs. Thank you!

        It doesn't supply a default because you've supplied a value (undef). If you want the default, don't supply something with that key as a parameter. You're presuming an idiom `replace undef parameters with the default value' where this code implements `replace unspecified parameters with the default value'.