Perl 中的标量和列表上下文
1 @backwards = reverse qw(yabba dabba doo);
2 $backwards = reverse qw(yabba dabba doo);
3
4 print @backwards; #gives doodabbayabba
5 print $backwards."\n"; #gives oodabbadabbay
6 print @backwards."\n"; #gives 3
在上面的代码中,为什么 line 6
给出 3 作为输出?如果它与 \n 连接,为什么它会转换为标量上下文?
In the above code why does line 6
give 3 as the output? Why does it convert to scalar context if its concatenated with a \n?
谢谢
您的问题最终是为什么 @backwards 在第 6 行的标量上下文中",其中引出了一个问题,我如何确定一个术语的上下文?".
Your question is ultimately "why is @backwards in scalar context in line 6", which begs the question, "how can I determine a term's context?".
上下文由术语周围的事物"(即它的上下文")决定.
Context is determined by "what is around" (i.e. its "context") the term.
如何确定术语的上下文?通过查看运算符/函数正在使用该术语.
How can I determine a term's context? By looking at the operator/function that is using the term.
如果你想了解@backwards 的上下文,你可以遵循哪些步骤?周围没有有用的 stackoverflow 人员来告诉您它的上下文吗?
What steps could you follow to figure out the context for @backwards yourself if you didn't have helpful stackoverflow folks around to tell you its context?
我们有
print @backwards."\n"
所以有两个操作符/函数.我们如何知道哪个提供了上下文到@backwards?通过咨询优先.在 perlop.pod 的顶部附近,我们有 Perl 的优先级图表(打印是列表运算符"):
so there are two operators/functions. How do we know which one provides context to @backwards? By consulting precedence. Near the top of perlop.pod we have Perl's precedence chart (print is a "list operator"):
left terms and list operators (leftward)
...
left + - .
...
nonassoc list operators (rightward)
太好了,现在我们需要知道打印是向左还是向右.通过咨询perlop 中的术语和列表运算符(向左)"部分(紧跟在优先级列表)我们看到 print 在这里向右,因为我们没有封闭括号中的参数.
Oh great, now we need to know whether print is leftward or rightward. By consulting the "Terms and List Operators (Leftward)" section in perlop (right after the precedence list) we see that print is rightward here, because we have not enclosed its arguments in parenthesis.
因此串联具有更高的优先级,因此串联为@backwards 提供了上下文.
So concatenation is higher precedence, so concatenation provides context to @backwards.
下一步是检查文档(再次 perlop)以进行连接:
Next step is to check the docs (perlop again) for concatenation:
Binary "." concatenates two strings.
字符串是标量,所以二进制."连接两个标量.
Strings are scalars, so binary "." concatenates two scalars.
我们终于拥有它了!
@backwards 具有标量上下文,因为串联为它的每个操作数.
@backwards has scalar context because concatenation provides scalar context to each of its operands.
呜.这很容易,不是吗:-)
Woo. That was easy, wasn't it :-)