perl: 为什么 $hashsize = keys $hash{$foo} 给出实验警告,我怎样才能写得更好?
perl: why does $hashsize = keys $hash{$foo} give experimental warning, and how can I write it better?
我有一个由两个因素决定的哈希值(我不知道正确的术语是什么),我是这样生成的:
if (exists $cuthash{$chr}{$bin}){
$cuthash{$chr}{$bin} += 1;
}else{
$cuthash{$chr}{$bin} = 1;
}
稍后我想获取散列的每个 $chr 部分的大小,这在我这样做时有效:
for my $chr (sort keys %cuthash){
my $hashsize = keys $cuthash{$chr};
...
}
但我收到警告:
keys on reference is experimental at ../test.pl line 115.
它有效,但显然它并不完美。什么是更好的方法?
谢谢
如果取消引用 hashref
my $hashsize = keys %{ $cuthash{$chr} };
那么应该没有警告。
如果您使用 ++
而不是 += 1
,则无需测试 $cuthash{$chr}{$bin}
是否存在,因为当其操作数为 undef 时它不会发出警告。随便写
++$cuthash{$chr}{$bin};
而不是整个 if
声明。
在这种情况下,直接或使用 each
提取散列值的本地副本可能更简洁。这样就不需要块来分隔引用表达式,所以你可以写 %$hashref
而不是 %{ $cuthash{$chr} }
。像这样
for my $chr (sort keys %cuthash) {
my $val = $cuthash{$chr};
my $hashsize = keys %$val;
...
}
或
while ( my ($key, $val) = each %cuthash) {
my $hashsize = keys %$val;
...
}
我相信您可以为 $val
想出一个更合理的名称来反映其用途
我有一个由两个因素决定的哈希值(我不知道正确的术语是什么),我是这样生成的:
if (exists $cuthash{$chr}{$bin}){
$cuthash{$chr}{$bin} += 1;
}else{
$cuthash{$chr}{$bin} = 1;
}
稍后我想获取散列的每个 $chr 部分的大小,这在我这样做时有效:
for my $chr (sort keys %cuthash){
my $hashsize = keys $cuthash{$chr};
...
}
但我收到警告:
keys on reference is experimental at ../test.pl line 115.
它有效,但显然它并不完美。什么是更好的方法?
谢谢
如果取消引用 hashref
my $hashsize = keys %{ $cuthash{$chr} };
那么应该没有警告。
如果您使用 ++
而不是 += 1
,则无需测试 $cuthash{$chr}{$bin}
是否存在,因为当其操作数为 undef 时它不会发出警告。随便写
++$cuthash{$chr}{$bin};
而不是整个 if
声明。
在这种情况下,直接或使用 each
提取散列值的本地副本可能更简洁。这样就不需要块来分隔引用表达式,所以你可以写 %$hashref
而不是 %{ $cuthash{$chr} }
。像这样
for my $chr (sort keys %cuthash) {
my $val = $cuthash{$chr};
my $hashsize = keys %$val;
...
}
或
while ( my ($key, $val) = each %cuthash) {
my $hashsize = keys %$val;
...
}
我相信您可以为 $val
想出一个更合理的名称来反映其用途