我似乎遇到了几种不同的方法来查找数组的大小。这三种方法有什么区别?

my @arr = (2);
print scalar @arr; # First way to print array size

print $#arr; # Second way to print array size

my $arrSize = @arr;
print $arrSize; # Third way to print array size

当前回答

使用int(@array),因为它威胁参数为标量。

其他回答

使用scalar关键字查找数组的大小:

print scalar @array;

要找出数组的最后一个索引,可以使用$# (Perl默认变量)。它给出了数组的最后一个索引。当数组从0开始时,我们通过给$#加1来获取数组的大小:

print "$#array+1";

例子:

my @a = qw(1 3 5);
print scalar @a, "\n";
print $#a+1, "\n";

输出:

3

3

例子:

my @a = (undef, undef);
my $size = @a;

warn "Size: " . $#a;   # Size: 1. It's not the size
warn "Size: " . $size; # Size: 2

打印数组大小的方法有很多种。以下是所有单词的含义:

假设数组是@arr = (3,4);

方法一:标量

这是获取数组大小的正确方法。

print scalar @arr;  # Prints size, here 2

方法二:索引号

$#arr给出数组的最后一个索引。因此,如果数组的大小为10,那么它的最后一个索引将是9。

print $#arr;     # Prints 1, as last index is 1
print $#arr + 1; # Adds 1 to the last index to get the array size

我们在这里加1,将数组视为0索引。但是,如果它不是从零开始的,这个逻辑就会失败。

perl -le 'local $[ = 4; my @arr = (3, 4); print $#arr + 1;'   # prints 6

上面的例子输出6,因为我们已经将它的初始索引设置为4。现在索引是5和6,分别是元素3和元素4。

方法3:

当数组在标量上下文中使用时,它将返回数组的大小

my $size = @arr;
print $size;   # Prints size, here 2

实际上,方法三和方法一是一样的。

第一种和第三种方法是相同的:它们在标量上下文中计算数组。我认为这是获取数组大小的标准方法。

第二种方法实际上返回数组的最后一个索引,它(通常)与数组大小不相同。

使用第二种方法,加1:

print $#arr + 1; # Second way to print array size