在Perl中计算数组元素

在Perl中计算数组元素

本文介绍了在Perl中计算数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取数组中的所有项目,而不是最后一个ID?

How do I get the total items in an array, NOT the last id?

我发现这两种方法都无法工作:

None of two ways I found to do this works:

my @a;
# Add some elements (no consecutive ids)
$a[0]= '1';
$a[5]= '2';
$a[23]= '3';

print $#a, "\n"; # Prints 23
print scalar(@a), "\n"; # Prints 24

我希望得到3 ...

I expected to get 3...

推荐答案

编辑:哈希与数组

正如cincodenada在注释中正确指出的,ysth给了一个更好的答案:我应该用另一个问题回答你的问题:你真的想使用Perl数组吗?哈希可能更合适。

As cincodenada correctly pointed out in the comment, ysth gave a better answer: I should have answered your question with another question: "Do you really want to use a Perl array? A hash may be more appropriate."

一个数组为所有可能的索引分配内存,直到到目前为止最大。在您的示例中,您分配24个单元格(但只使用3)。相反,哈希只为实际使用的字段分配空间。

An array allocates memory for all possible indices up to the largest used so-far. In your example, you allocate 24 cells (but use only 3). By contrast, a hash only allocates space for those fields that are actually used.

数组解决方案:scalar grep

这里有两种可能的解决方案(见下面的解释):

Here are two possible solutions (see below for explanation):

print scalar(grep {defined $_} @a), "\n";  # prints 3
print scalar(grep $_, @a), "\n";            # prints 3

说明:添加 $ a [23] ,你的数组真的包含24个元素---但是大多数是未定义的(它也评价为false)。您可以计算已定义元素的数量(如第一个解决方案中所做的)或真实元素的数量(第二个解决方案)。

Explanation: After adding $a[23], your array really contains 24 elements --- but most of them are undefined (which also evaluates as false). You can count the number of defined elements (as done in the first solution) or the number of true elements (second solution).

有什么区别?如果你设置 $ a [10] = 0 ,那么第一个解决方案将对其进行计数,但第二个解决方案不会(因为0是假的,但是定义)。如果您设置 $ a [3] = undef ,则解决方案都不会计算。

What is the difference? If you set $a[10]=0, then the first solution will count it, but the second solution won't (because 0 is false but defined). If you set $a[3]=undef, none of the solutions will count it.

哈希解决方案(按yst)

正如另一个解决方案所建议的,您可以使用哈希并避免所有问题:

As suggested by another solution, you can work with a hash and avoid all the problems:

$a{0}  = 1;
$a{5}  = 2;
$a{23} = 3;
print scalar(keys %a), "\n";  # prints 3

此解决方案计算零值和undef值。

This solution counts zeros and undef values.

这篇关于在Perl中计算数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 03:37