Perl中的标量vs列表上下文 [英] Scalar vs list context in Perl

查看:65
本文介绍了Perl中的标量vs列表上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在O'Reilly的书中发现了一个奇怪的例子:

I found an example in an O'Reilly book a little weird:

@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 /被视为一个列表,而reverse qw/ yabba dabba doo /被视为("doo","dabba","yabba").

The book says 'reverse something' gives a list context, so I guess qw/ yabba dabba doo / is seen as a list and reverse qw/ yabba dabba doo / as ('doo', 'dabba', 'yabba').

$backward = something来了,它暗示某事是一个标量,所以我期待的结果是'doo dabba yabba',但这是不同的:'oodabbadabbay'.

So comes the $backward = something which implies something is a scalar, so I was expecting the result 'doo dabba yabba', but it is différent: 'oodabbadabbay'.

我认为,原因是因为无法直接将列表设置为标量.因此,我进行了scalar2测试:仅打印列表中的最新项目.为什么?为什么不参加scalar1测试?

I thought, the reason was because one cannot set a list to a scalar directly. So I made the scalar2 test: only the latest item in the list is printed. Why? Why not in the scalar1 test?

标量测试输出如何工作?

How do the scalar tests output work?

推荐答案

对于该行:

$backward = reverse qw/ yabba dabba doo /;

您正在从反方向请求标量.反向Perldoc表示:

You are requesting a scalar here from reverse. The perldoc for reverse says:

在标量上下文中,将 LIST的元素并返回一个字符串 值中的所有字符 相反的顺序.

In scalar context, concatenates the elements of LIST and returns a string value with all characters in the opposite order.

因此它返回每个颠倒的字母.

So it returns each of the letters reversed.

对于 $ notbackward = qw/yabba dabba doo/; qw//的perldoc表示:

For $notbackward = qw/ yabba dabba doo /; the perldoc for qw// says:

求出单词列表 使用以下方法从STRING中提取 嵌入空格作为单词 定界符.可以理解为 大致等同于:

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:

               split(’ ’, q/STRING/);

区别在于它在以下位置生成真实列表 编译时间,并在标量上下文中 返回列表中的最后一个元素.

the differences being that it generates a real list at compile time, and in scalar context it returns the last element in the list.

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

So requesting the scalar only returns the last item in the list.

这篇关于Perl中的标量vs列表上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆