in reply to Optional and default parameters for a subroutine

Maybe I'm missing something crucial here, but I've always liked the simplified:

sub my_function { my %args = @_; # Now take care of default arguments... $args{arg1} ||= 'default value1'; $args{arg2} ||= 'default value2'; }

It basically evaluates $args{arg1}, and if it evaluates to true, they must have passed it, otherwise, assign the default value.

Replies are listed 'Best First'.
Re^2: Optional and default parameters for a subroutine
by Joost (Canon) on Aug 29, 2005 at 20:15 UTC
    But as you noted, that will only work if your arguments are always true, or that false indicates "default value". The nice thing about using the %hash = ( default => "value", @_ ); construct (besides being shorter) is that it works for all values.

    To do the same with explicit testing you'd need

    $args{arg1} = 'default value1' unless exists $args{arg1};
      Although I wrote the phrase, "if it evaluates to true," I didn't consider its implications. Thanks for pointing that out.