简体   繁体   English

Perl中标量上下文中的数组

[英]Array in scalar context in Perl

In Perl, if you will assign an array to a scalar, you will get length of that array. 在Perl中,如果要将数组分配给标量,则将获得该数组的长度。

Example: 例:

my @arr = (1,2,3,4);
my $x = @arr;

Now if you check the content of $x , you will find that $x contains the length of @arr array. 现在,如果你检查$x的内容,你会发现$x包含@arr数组的长度。

I want to know the reason why Perl does so. 我想知道Perl之所以这样做的原因。 What is the reason behind it? 它背后的原因是什么? I try at my level but could not find any good reason. 我尝试了我的水平,但找不到任何好的理由。 So, can someone help me understand the reason behind the scene which is taking place? 那么,有人能帮我理解正在发生的场景背后的原因吗?

Perl uses contexts where other languages use functions to get some info or convert the value between different types. Perl使用上下文,其他语言使用函数来获取某些信息或在不同类型之间转换值。 The concept of context is thoroughly explained in perldata manual page ( man perldata ). perldata手册页( man perldata )中详细解释了上下文的概念。

In Perl, the same data look differently under different context. 在Perl中,相同的数据在不同的上下文中看起来不同。 An array looks like a list of its elements in list context, while it looks like number of its elements in scalar context. 数组看起来像列表上下文中的元素列表,而它看起来像标量上下文中的元素数。

How else could it possibly look in scalar context? 在标量语境中它怎么可能看起来?

  • It could be the fist element of the array. 它可能是阵列的第一个元素。 This can be done with my ($x) = @arr; 这可以用my ($x) = @arr; or my $x = shift @arr; 或者my $x = shift @arr; or my $x = $arr[0]; 或者my $x = $arr[0]; .
  • It could be the last element of the array. 它可能是数组的最后一个元素。 This can be done with my ($x) = reverse @arr; 这可以用my ($x) = reverse @arr; or my $x = pop @arr; 或者my $x = pop @arr; or my $x = $arr[-1]; 或者my $x = $arr[-1]; .

I cannot think of any other reasonable way to make a scalar from an array. 我想不出任何其他合理的方法来从数组中生成标量。 Obviously using array length as its scalar value is better than these two, because it is somewhat global property of the array, while these two are fairly local. 显然使用数组长度作为其标量值比这两个更好,因为它是数组的某种全局属性,而这两个是相当本地的。 And it is also very logical when you look at typical use of array in scalar context: 当您在标量上下文中查看数组的典型用法时,它也是非常合乎逻辑的:

die "Not enough arguments" if @ARGV < 5;

You can read < quite naturally as “is smaller than”. 您可以阅读<非常自然,因为“小于”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM