为什么在 Perl 中打印后不能立即获得文字列表切片?
我发现我可以做这样的事情:
print STDOUT (split /\./, 'www.stackoverflow.com')[1];
并打印“stackoverflow”。但是, this: 的
print +(split /\./, 'www.stackoverflow.com')[1];
作用相同,并且 this:
print (split /\./, 'www.stackoverflow.com')[1];
是一个语法错误。那么这里究竟发生了什么?我一直认为一元加号在任何情况下都不执行任何操作。如果“print FILEHANDLE EXPR”有效,我会想象“print EXPR”总是同样有效。有什么见解吗?
I see I can do something like this:
print STDOUT (split /\./, 'www.stackoverflow.com')[1];
and "stackoverflow" is printed. However, this:
print +(split /\./, 'www.stackoverflow.com')[1];
does the same, and this:
print (split /\./, 'www.stackoverflow.com')[1];
is a syntax error. So what exactly is going on here? I've always understood the unary plus sign to do nothing whatsoever in any context. And if "print FILEHANDLE EXPR" works, I would have imagined that "print EXPR" would always work equally well. Any insights?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您没有启用警告。在
print(...)[1]
情况下,括号集被视为函数语法的一部分。来自,perldoc -f print:
另请参阅 为什么不打印换行符这个 Perl 代码?
You do not have warnings enabled. In the
print(...)[1]
case, the set of parentheses are regarded as part of the function syntax.From, perldoc -f print:
See also Why aren't newlines being printed in this Perl code?
print
的perldoc
包含以下内容:print
始终在 LIST 上下文中计算其参数。说一下
就可以了。但是,当您说
解析器在看到第一个
(
后需要一个 LIST,并在看到结束的)
时认为 LIST 是完整的。[0]
不会被解释为对任何内容进行操作,因此您会收到语法错误。其他可以将 LIST 作为第一个参数的 Perl 函数的行为方式相同:
perldoc
forprint
includes this nugget:print
always evaluates its arguments in LIST context.To say
is ok. But when you say
the parser expects a LIST after it sees the first
(
, and considers the LIST to be complete when it sees the closing)
. The[0]
is not interpreted as operating on anything, so you get a syntax error.Other Perl functions that can take a LIST as the first argument behave the same way: