@backwards = reverse qw/ yabba dabba doo /; print "list context: @backwards\n"; $backward = reverse qw/ yabba dabba doo /; print "scalar1 context: $backward\n"; $notbackward = qw/ yabba dabba doo /; print "scalar2 context: $notbackward\n"; print "print context: ",reverse qw/ yabba dabba doo /; print "\n";
输出是:
list context: doo dabba yabba scalar1 context: oodabbadabbay scalar2 context: doo print context: doodabbayabba
我不明白的是scalar1上下文:
这本书说“反向某事”给出了一个列表上下文,所以我猜qw / yabba dabba doo /被视为一个列表并反向qw / yabba dabba doo / as(‘doo’,’dabba’,’yabba’).
因此,$backward =暗示某事物是标量的东西,所以我期待结果’doo dabba yabba’,但它是不同的:’oodabbadabbay’.
我想,原因是因为无法直接将列表设置为标量.所以我做了scalar2测试:只打印列表中的最新项目.为什么?为什么不在scalar1测试?
标量测试输出如何工作?
解决方法
$backward = reverse qw/ yabba dabba doo /;
你正在反向请求标量.反向的perldoc说:
In scalar context,concatenates the
elements of LIST and returns a string
value with all characters in the
opposite order.
所以它返回每个反转的字母.
对于
$notbackward = qw / yabba dabba doo /;
qw //的perldoc说:
Evaluates to a list of the words
extracted out of STRING,using
embedded whitespace as the word
delimiters. It can be understood as
being roughly equivalent to:06001
the differences being that it generates a real list at
compile time,and in scalar context it
returns the last element in the list.
因此,请求标量只返回列表中的最后一项.