[英]How can I find the number of keys in a hash in Perl?
如何在散列中找到键的数量,比如使用$#
作为数组?
scalar keys %hash
or just 要不就
keys %hash
if you're already in a scalar context, eg my $hash_count = keys %hash
or print 'bighash' if keys %hash > 1000
. 如果你已经在标量上下文中,例如
my $hash_count = keys %hash
或者print 'bighash' if keys %hash > 1000
。
Incidentally, $#array
doesn't find the number of elements, it finds the last index. 顺便说一句,
$#array
没有找到元素的数量,它找到了最后一个索引。 scalar @array
finds the number of elements. scalar @array
查找元素的数量。
we can use like this too 我们也可以这样使用
my $keys = keys(%r) ;
print "keys = $keys" ;
0+(keys %r)
But not after Perl 5.10: 但不是在Perl 5.10之后:
use feature ":5.10";
my %p = ();
say $#%p;
# $# is no longer supported
and worse: 更糟糕的是:
use feature ":5.10";
my %p = (a=>1, b=>2, c=>3);
say $#{%p};
# -1
print scalar keys %hash;
or 要么
$X = keys %hash;
print $X;
keys %hash
returns the value of keys in the list context that further changes into the scalar context (when assigning to scalar variable). keys %hash
返回列表上下文中键的值,该值进一步更改为标量上下文(当分配给标量变量时)。
This will work in easy way and for any size of a hash. 这将以简单的方式和任何大小的哈希工作。
print scalar keys %hash; print scalar keys%hash;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.