加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

标量与Perl中的列表上下文

发布时间:2020-12-16 06:10:51 所属栏目:大数据 来源:网络整理
导读:我在O’Reilly的书中发现了一个有点奇怪的例子: @backwards = reverse qw/ yabba dabba doo /;print "list context: @backwardsn";$backward = reverse qw/ yabba dabba doo /;print "scalar1 context: $backwardn";$notbackward = qw/ yabba dabba doo /
我在O’Reilly的书中发现了一个有点奇怪的例子:

@backwards = reverse qw/ yabba dabba doo /;
print "list context: @backwardsn";
$backward = reverse qw/ yabba dabba doo /;
print "scalar1 context: $backwardn";
$notbackward = qw/ yabba dabba doo /;
print "scalar2 context: $notbackwardn";
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.

因此,请求标量只返回列表中的最后一项.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读