Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re^3: Correct idiom for default parameters

by BrowserUk (Pope)
on Apr 28, 2010 at 19:00 UTC ( #837373=note: print w/ replies, xml ) Need Help??


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

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.


Comment on Re^3: Correct idiom for default parameters
Download Code
Replies are listed 'Best First'.
Re^4: Correct idiom for default parameters
by LanX (Canon) on Apr 28, 2010 at 22:50 UTC
    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

      Sorry, I don't follow?

      Passing undef gives exactly the effect I would expect and desire. That of accepting the default for that parameter:

      test( 'a', undef, 'c' );; p1:a; p2:2; 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.
        well, thats not the result I get:

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

        p1:a; p2:2; p3:3

        $p3 ne 'c'

        the first undef value omits the shift, all following parameters will be replaced by defaults! You need an explicit shift after the colon!

        Cheers Rolf

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://837373]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (7)
As of 2015-07-29 05:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (260 votes), past polls