计数数组元素在Perl [英] Counting array elements in Perl

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

问题描述

我需要在数组的总的项目,而不是最后的ID,没有两种方式,我发现这样做的工作:

I need to get the total items in array, NOT the last id, none of both 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..

感谢您提前。

推荐答案

编辑:哈希与数组

由于CIN codenada正确的评论中指出,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.

阵列解决方案:标量的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种元素---但其中大部分是不确定的(这也评估为假)。可以计数(如在第一溶液进行)定义​​的元素的数量或真元素的数量(第二溶液)。

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).

有什么区别?如果设置美元[10] = 0 ,然后第一个解决方案将依靠它,但第二个解决方案将不会(因为0是假的,但定义)。如果设置 $ a [3] =民主基金,没有任何解决方案都会算吧。

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

此解决方案计数零和民主基金的值。

This solution counts zeros and undef values.

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

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