如何得到没有的计数。 perl 6 %HASH 中的键数?

How to get the count of no. of keys in a perl 6 %HASH?

谁能帮忙算一下。哈希中的键,在 PERL 6 中?寻找没有手动循环的东西。

提前致谢!

编辑:到目前为止尝试了以下但没有成功。

my %hash =  1 => "one", 2 => <21,22,23>, 3 => "three"  ;

my $count = %hash.keys [ makes it a flat list ]
my $count = %hash.count [no such method]
my $count = keys %hash [provides all the keys but not the count]

此答案哈希已在 OP 编辑​​之前发布:

您的哈希初始化有问题

my  %hash = {"1" => "one", "2" => "21,22,23", "3" => "three"} ;

应该是

my  %hash = ("1" => "one", "2" => "21,22,23", "3" => "three") ;

现在回答您的实际问题试试:

试试这个:

$count=1;
for %hash.keys.sort -> $key {  #no need to sort though
       # say "$key %hash{$key}";
        $count++;
    }
print "$count\n";

感谢 IRC Perl 6 Chat 社区,这是计数的方式。哈希键,native/inbuilt functions/methods.

%_Host@User> ./h.p6
Count is 3
Count is 3
%_Host@User>
%_Host@User> cat h.p6
#!/usr/bin/perl6

use v6 ;

my %hash = (1 => <1 2 3>, 2 => "ljsf", 3 => "AFDS") ;

say "Count is " ~ +%hash ;
say "Count is " ~ %hash.elems ;
%_Host@User>

谢谢。

在 perl5 中,您可以将散列转换为标量,它就变成了计数。您也可以在 perl6 中这样做:

%hash.Int;  
# => 3
+%hash
# => 3

你还有elems方法:

%hash.elems;  
# => 3

哈希是 Cool, so you can even avoid the .elems 调用,只需将哈希用作数字:

my %h = :42a, :72b;
say +%h; # 2
say "We need {42 + %h} spaces to store stuff"; # We need 44 spaces to store stuff