是否可以将子例程原型化为 $$&在 Perl 中?
只是出于好奇,我尝试了一下原型设计,但似乎子例程的原型 &
只允许出现在第一个位置。
当我编写
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
&
原型字符仅在原型中的第一项时才采用块形式。这只是 perl 原型解析器工作方式的限制。您始终可以使用
sub
关键字创建一个匿名子例程,该子例程可以在没有原型的情况下作为任何位置的参数正常工作。如果您真的想在没有
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.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).引用文档(
perldoc perlsub
):Quoting the documentation (
perldoc perlsub
):