perl:为什么$ hashsize = keys $ hash {$ foo}给出实验警告,我怎样才能更好地编写它?

Dan*_*iel 4 perl hash warnings

我有一个哈希由两个因素决定(我不知道这是什么正确的术语),我生成如下:

if (exists $cuthash{$chr}{$bin}){
    $cuthash{$chr}{$bin} += 1;
}else{
    $cuthash{$chr}{$bin} = 1;
}
Run Code Online (Sandbox Code Playgroud)

我后来想要获取哈希的每个$ chr部分的大小,这在我做的时候有效:

for my $chr (sort keys %cuthash){
    my $hashsize = keys $cuthash{$chr};
    ...
}
Run Code Online (Sandbox Code Playgroud)

但我得到警告:

keys on reference is experimental at ../test.pl line 115.
Run Code Online (Sandbox Code Playgroud)

它有效,但显然它并不完美.什么是更好的方法?

谢谢

dgw*_*dgw 8

如果取消引用hashref

my $hashsize = keys %{ $cuthash{$chr} };
Run Code Online (Sandbox Code Playgroud)

那应该没有警告.

  • @Daniel:它更"好",因为`keys`只适用于哈希,正如你所期望的那样.值`$ cuthash {$ chr}`是一个恰好是哈希引用的*标量*,因此历史上你的语法将被拒绝.因为在这里传递引用而不是正确的哈希值大多是明确的,所以Perl 5的第14版引入了一个允许你这样做的实验性增强; 但是在实验中它可能会发生变化,所以不应该在生产代码中使用.顺便说一下,尝试使用Googling for*Perl嵌套哈希*并查看[*Perl Data Structures Cookbook*](http://perldoc.perl.org/perldsc.html) (2认同)
  • `keys $ hash_or_array_ref`是实验性的,因为在某些情况下不清楚它的行为应该是什么.使用`keys%$ hash_ref`或`keys @ $ array_ref`可以避免这些情况. (2认同)