Perl中标量和列表上下文有什么区别? [英] What is the difference between the scalar and list contexts in Perl?

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

问题描述

Perl中标量和列表上下文之间有什么区别,并且在其他语言(例如Java或Javascript)中是否有任何相似之处?

What is the difference between the scalar and list contexts in Perl and does this have any parallel in other languages such as Java or Javascript?

推荐答案

Perl中的各种运算符都是上下文敏感的,并且在列表和标量上下文中产生不同的结果.

Various operators in Perl are context sensitive and produce different results in list and scalar context.

例如:

my(@array) = (1, 2, 4, 8, 16);
my($first) = @array;
my(@copy1) = @array;
my @copy2  = @array;
my $count  = @array;

print "array: @array\n";
print "first: $first\n";
print "copy1: @copy1\n";
print "copy2: @copy2\n";
print "count: $count\n";

输出:

array: 1 2 4 8 16
first: 1
copy1: 1 2 4 8 16
copy2: 1 2 4 8 16
count: 5

现在:

  • $first包含1(数组的第一个元素),因为my($first)中的括号提供了数组上下文,但是$first中只有一个值用于空格.
  • @copy1@copy2都包含@array的副本,
  • $count包含5,因为它是一个标量上下文,并且@array计算标量上下文中数组中的元素数量.
  • $first contains 1 (the first element of the array), because the parentheses in the my($first) provide an array context, but there's only space for one value in $first.
  • both @copy1 and @copy2 contain a copy of @array,
  • and $count contains 5 because it is a scalar context, and @array evaluates to the number of elements in the array in a scalar context.

也可以构建更详细的示例(结果是读者的练习):

More elaborate examples could be constructed too (the results are an exercise for the reader):

my($item1, $item2, @rest) = @array;
my(@copy3, @copy4) = @array, @array;

在我所知道的其他语言中,列表和标量上下文没有直接的平行线.

There is no direct parallel to list and scalar context in other languages that I know of.

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

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