in reply to Re: Correct idiom for default parameters
in thread Correct idiom for default parameters

more condensed:

sub defaults { my ($d1,$d2,$d3) = map { @_ ? shift : $_ } (1,2,3); print("$d1 $d2 $d3\n"); } defaults(); defaults(0); defaults(0, 0); defaults(0, 0, 0);

plz note: this solution depends on the number of defaulted parameters...

Cheers Rolf

Replies are listed 'Best First'.
Re^3: Correct idiom for default parameters
by mrider (Beadle) on Apr 28, 2010 at 22:52 UTC

    That looks pretty good!

    And to answer your question in the post previous to this one, no I don't expect there to be an "undef" in the middle. The overwhelming majority of the cases there is one parameter that is optional. Which means that the predominant use will look like this:

    sub defaults { my ($self, $param) = map { @_ ? shift : $_ } (1); print($param); }

    I found one place where it would be nice to have two optional parameters, but I'm debating refactoring that sub routine.

      >  my ($self, $param) = map { @_ ? shift : $_ } (1);

      ehm ... $self defaults to 1??? ;-)

      IMHO better catch $self in a separate shift!

      UPDATE:

      > The overwhelming majority of the cases there is one parameter that is optional. Which means that the predominant use will look like this:

      Then better avoid this construct!

      IMHO it's much clearer (and faster) to write

      my ($self,$a,$b,$c,$d)=@_; $d = 4 unless defined $d;

      Cheers Rolf