in reply to Correct idiom for default parameters

This assumes 5.10 or higher:

sub defaults { my $self = shift; my $default1 = shift // 1; my $default2 = shift // 2; my $default3 = shift // 3; print("$default1 $default2 $default3\n"); }

Though I would never claim this is the "correct" idiom. Celebrate TIMTOWTDI!

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

    Ack! 5.8.8 here (sigh).

    Thanks for the suggestion though.

      This is 5.8 accessible and might even be more palatable?

      Updated per LanX's correction below.

      sub test{ my( $p1, $p2, $p3) = map{ scalar @_ ? shift : $_ }( 1, 2, 3 ); print "p1:$p1; p2:$p2; p3:$p3"; };; test();; p1:1; p2:2; p3:3 test( 'a' );; p1:a; p2:2; p3:3 test( 'a', 'b', 'c' );; p1:a; p2:b; p3:c

      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.
        careful!

        passing undef in between will break your idiom.

        IMHO better check scalar @_ or care explicitly about passing undef !

        sub defaults { my( $p1, $p2, $p3) = map{ defined $_[0] ? shift : $_ }( 1, 2, 3 ); + print "p1:$p1; p2:$p2; p3:$p3\n"; }; defaults(undef, 0, 0);

        Cheers Rolf