强制成为标量
#!/usr/bin/perl
use Modern::Perl;
while (<>)
{ chomp;
say reverse;
}
上面的代码不起作用,但是当我将倒数第二行更改为 say scalar reverse;
时,它就可以正常工作。为什么我需要显式地强制它成为标量? Perl 不能 DWIM 吗?
#!/usr/bin/perl
use Modern::Perl;
while (<>)
{ chomp;
say reverse;
}
The above code doesn't work but when I change 2nd last line to say scalar reverse;
then it works fine. Why do I need to force it to be a scalar explicitly? Can't Perl DWIM?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我对文档的理解正确的话,
reverse
通常在列表上运行。在不带参数的列表上下文中,它返回一个空列表,并且默认情况下不会将其分配到任何地方。在您的示例中,假设输出未更改的$_
;强制
reverse
进入标量上下文会更改其行为并使其反转字符串,并默认使用$_
。由于say
可用于打印列表和标量,因此它不会强制将其参数放入标量上下文中。Perl 可能会执行 DWIM,只是针对给定的“I”值。
详细了解反向操作在以下情况下的作用:
If I understand the documentation right,
reverse
normally operates on lists. In a list context used without arguments, it returns an empty list and by default doesn't assign it anywhere. In your example, say outputs the unchanged$_
;Forcing
reverse
into scalar context changes its behaviour and makes it reverse character strings, and use$_
by default. Becausesay
can be used to print lists as well as scalars, it doesn't force its arguments into scalar context.Perl probably does DWIM, just for given values of "I".
A breakdown of what reverse does when:
正如记录的,
reverse
反转了元素的顺序在列表上下文中使用时的参数列表。例如,反转 'a'、'b'、'c'
返回'c'、'b'、'a'
。是的,它可以执行您想要的操作(不存在参数表达式时的标量行为)。
不过,这可能会令人困惑。我想不出任何其他运算符会因为缺少参数表达式(而不是仅仅缺少参数)而改变行为。
As documented,
reverse
reverses the order of the elements of the argument list when used in list context. For example,reverse 'a', 'b', 'c'
returns'c', 'b', 'a'
.Yes, it could do what you want (scalar behaviour when no argument expression is present).
It could be confusing, though. I can't think of any other operator that changes behaviour based on a lack of an argument expression (as opposed to just lack of arguments).