是否可以将子例程原型化为 $$&在 Perl 中?

发布于 2024-12-19 10:43:03 字数 671 浏览 0 评论 0原文

只是出于好奇,我尝试了一下原型设计,但似乎子例程的原型 & 只允许出现在第一个位置。

当我编写

sub test (&$$) {
    do_something;
}

并调用它

test {doing_something_else} 1,2;

时,它就起作用了。

当我像这样制作原型

sub test ($$&) {
    do_something;
}

并再次调用它时,因为

test 1,2 {doing_something_else};

它不起作用。我尝试了各种排列,但似乎没有任何效果。

我错过了什么,还是不可能?如果没有,为什么?

(当然,我可能需要指定,我成功尝试了调用 test(1, 2, sub{foo}) 的选项,但它看起来并不像上面最后一个示例中的选项那么性感(并且对于我什至不需要原型设计);我希望能够实现 if () {} else {} 等结构的语法,或者更重要的是, try () catch () {} 或switch () case (){},但我猜这就是为什么这些构造尚未在 Perl 中实现的原因)

Just a curiosity, I have played around with prototyping a bit, but it seems that the prototype & for a subroutine is only allowed in the first position.

When I write

sub test (&$) {
    do_something;
}

and call it as

test {doing_something_else} 1,2;

it works.

When I prototype like this

sub test ($&) {
    do_something;
}

and again call it as

test 1,2 {doing_something_else};

it doesn't work. I tried with various permutations, but nothing seems to deliver.

Am I missing something, or is it not possible? And if not, why?

(I maybe need to specify, that I successfully tried the option of calling test(1, 2, sub{foo}), of course, but it doesn't look quite as sexy as the option in the last example above (and for that I don't even need prototyping); I would like to be able to implement the syntax of structures like if () {} else {}, etc. or, more to the point, try () catch () {} or switch () case (){}, but I guess that's why those constructs have not yet been implemented in Perl)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

笑着哭最痛 2024-12-26 10:43:03

& 原型字符仅在原型中的第一项时才采用块形式。这只是 perl 原型解析器工作方式的限制。

您始终可以使用 sub 关键字创建一个匿名子例程,该子例程可以在没有原型的情况下作为任何位置的参数正常工作。

test 1, 2, sub {doing_something_else};

如果您真的想在没有 sub 的情况下编写它,但不在第一个位置,您可以使用 Devel::Declare 来为测试子例程编写您自己的解析规则(这是一个高级主题)。

The & prototype character only takes the block form when it is the first item in a prototype. This is just a limitation of the way perl's prototype parser works.

You could always use the sub keyword to create an anonymous subroutine that works fine as an argument in any position without a prototype.

test 1, 2, sub {doing_something_else};

If you really really want to write it without the sub but not in the first position, you could have fun playing around with Devel::Declare to write your own parse rules for the test subroutine (this is an advanced topic).

谜兔 2024-12-26 10:43:03

引用文档(perldoc perlsub):

一个“&”需要一个匿名子例程,如果将其作为第一个传递
参数,不需要“sub”关键字或后续逗号。

Quoting the documentation (perldoc perlsub):

An "&" requires an anonymous subroutine, which, if passed as the first
argument, does not require the "sub" keyword or a subsequent comma.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文