将数组传递给 Perl 长度子例程时会发生什么?

What happens when an array is passed to the Perl length subroutine?

这是我的代码:

my @list = qw (The quick brown fox jumps over the lazy Perl programmer); 
my @list1 = qw (Sparta F R I j h df dfsd dfsdf ); 
my @list2 = qw (The quick brown fox jumps over the lazy Perl programmer); 
print length(@list), "\n"; 
print length(@list1), "\n"; 
print length(@list2), "\n";

我得到的输出:

2
1
2

输出背后的原因是什么?它不应该给我第一个元素的长度吗?

这有很好的记录here and here

The length function always works on strings and it creates SCALAR context for its parameters. Hence if we pass an array as a parameter, that array will be placed in SCALAR context and it will return the number of elements in it.

在数组上调用lengthreturns数组中元素数量的长度。

因此:

  • 一个 10 元素数组 length(@list) returns 2 (length(10) == 2)
  • 一个 9 元素数组 length(@list1) returns 1 (length(9) == 1)

此上下文中的数组被计算为它的长度计数。由于第一个数组包含 10 个元素,因此 length() 函数获取字符串“10”作为其参数和 returns 2.

第二个数组的长度为 9 个,长度为 1 个字符,因此长度 returns 1.