最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

raku - How to explicitly use the default value of a parameter? - Stack Overflow

programmeradmin4浏览0评论

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
  • I don't know of an idiomatic solution. I'm working on an answer I figured out. It starts with the basic idea of introspecting the signature to pull out the default and passing that. So 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
  • Thsnk, I think we can do everything with Raku, but introspecting the signature is also a bit too hacky for this case. :) – fingolfin Commented 23 hours ago
Add a comment  | 

1 Answer 1

Reset to default 3

I 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.

发布评论

评论列表(0)

  1. 暂无评论