Why can't I have a literal list slice right after a print in Perl?

折月煮酒 提交于 2019-12-23 19:12:29

问题


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?


回答1:


You do not have warnings enabled. In the print(...)[1] case, the set of parentheses are regarded as part of the function syntax.

print (...) interpreted as function at C:\Temp\t.pl line 4.

From, perldoc -f print:

Also be careful not to follow the print keyword with a left parenthesis unless you want the corresponding right parenthesis to terminate the arguments to the print—interpose a + or put parentheses around all the arguments.

See also Why aren't newlines being printed in this Perl code?




回答2:


perldoc for print includes this nugget:

Also be careful not to follow the print keyword with a left parenthesis unless you want the corresponding right parenthesis to terminate the arguments to the print--interpose a "+" or put parentheses around all the arguments.

print always evaluates its arguments in LIST context.

To say

print (split /\./, 'www.stackoverflow.com')

is ok. But when you say

print (split /\./, 'www.stackoverflow.com')[0]

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.

print "abc","def";       # prints "abcdef"
print ("abc","def");     # prints "abcdef"
print ("abc"), "def";    # prints "abc"


Other Perl functions that can take a LIST as the first argument behave the same way:

warn ($message),"\n"   # \n not passed to warn, line # info not suppressed

system ("echo"),"x"    # not same as system("echo","x") or system "echo","x"
                       #    or system(("echo"),"x")


来源:https://stackoverflow.com/questions/1683158/why-cant-i-have-a-literal-list-slice-right-after-a-print-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!