Let's say we have the following subroutine:
sub test($arg = 'defaut value') { say $arg }
And we want to pass some argument that will cause the subroutine to use the default value, something like this:
my $undefined-value;
test $undefined-value // Nil; # don't work, prints "Nil"
How to accomplish this in the most idiomatic way possible?
I found this solution, but it looks a bit hacky:
test |($undefined-value // Empty); # works, print "defaut value"
Let's say we have the following subroutine:
sub test($arg = 'defaut value') { say $arg }
And we want to pass some argument that will cause the subroutine to use the default value, something like this:
my $undefined-value;
test $undefined-value // Nil; # don't work, prints "Nil"
How to accomplish this in the most idiomatic way possible?
I found this solution, but it looks a bit hacky:
test |($undefined-value // Empty); # works, print "defaut value"
Share
Improve this question
edited yesterday
fingolfin
asked yesterday
fingolfinfingolfin
7862 silver badges10 bronze badges
2
|
1 Answer
Reset to default 3I guess the most idiomatic way is to:
sub test($arg? is copy) {
$arg //= 'default value';
say $arg;
}
test Any; # default value
which would allow you to pass any undefined value as the argument
Alternately, you could use a multi:
multi sub test(Any:U $) { test }
multi sub test(Any:D $arg = "default value") { say $arg }
test Any; # default value
The first candidate will catch any undefined value, and then call the candidate without any arguments, which will then set the default value.
test &test.signature.params[0].default.()
. (I could swear I wrote that as part of another SO answer but I've been unable to find it.) I'm currently working on a packaging of that basic idea into a wrapped version of a sub so that use of a*
(whatever star) as an argument turns that argument into its default. This would not be a solution for routines that accept a*
as a meaningful argument but whatever. :) – raiph Commented yesterday