in reply to Correct idiom for default parameters
if you are restricted to positional parameters, what about this ...
sub defaults { my $d1= ( @_ ? shift : 1 ); my $d2= ( @_ ? shift : 2 ); my $d3= ( @_ ? shift : 3 ); print("$d1 $d2 $d3\n"); } defaults(); defaults(0); defaults(0, 0); defaults(0, 0, 0); __DATA__ 1 2 3 0 2 3 0 0 3 0 0 0
Cheers Rolf
UPDATE: precedence rules allow to omit the parens.
UPDATE from the example you gave I assumed that you don't plan to pass undef in the middle of parameters and expect this to be checked... otherwise all these solutions are too simplified and you have to check explicitly with defined. But in this case I really recommend using named parameters!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Correct idiom for default parameters
by LanX (Saint) on Apr 28, 2010 at 20:37 UTC | |
by mrider (Beadle) on Apr 28, 2010 at 22:52 UTC | |
by LanX (Saint) on Apr 28, 2010 at 22:58 UTC | |
|
Re^2: Correct idiom for default parameters
by LanX (Saint) on Apr 28, 2010 at 20:52 UTC |