繁体   English   中英

如何在Perl中找到哈希中的键数?

[英]How can I find the number of keys in a hash in Perl?

如何在散列中找到键的数量,比如使用$#作为数组?

scalar keys %hash

要不就

keys %hash

如果你已经在标量上下文中,例如my $hash_count = keys %hash或者print 'bighash' if keys %hash > 1000

顺便说一句, $#array没有找到元素的数量,它找到了最后一个索引。 scalar @array查找元素的数量。

我们也可以这样使用

my $keys = keys(%r) ;
print "keys = $keys" ;

 0+(keys %r) 

但不是在Perl 5.10之后:

use feature ":5.10";
my %p = ();
say $#%p;

# $# is no longer supported

更糟糕的是:

use feature ":5.10";
my %p = (a=>1, b=>2, c=>3);
say $#{%p};

# -1
print scalar keys %hash;

要么

$X = keys %hash;
print $X;

keys %hash返回列表上下文中键的值,该值进一步更改为标量上下文(当分配给标量变量时)。

这将以简单的方式和任何大小的哈希工作。

print scalar keys%hash;

暂无
暂无

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

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