我需要测试,我的hashref是否包含0个元素.
我用过这段代码:
我用过这段代码:
$self = { fld => 1 }; %h = ( "a" => "b" ); $self->{href} = { %h }; print STDERR $self->{href}{ "a" }; print STDERR "\n"; print "size of hash: " . keys( %h ) . ".\n"; print "size of hashref: " . keys( $self->{href} ) . ".\n";
它适用于perl 5.16,但是使用perl 5.10失败:
Type of arg 1 to keys must be hash (not hash element) at - line 7,near "} ) " Execution of - aborted due to compilation errors.
解决方法
如果你使用
%hash
对于哈希,你会使用
%{ $hash }
作为参考,所以它是
keys %{ $self->{href} }
注意:在某些版本的Perl中,键接受引用.然而,这是一个被放弃的实验性功能.一个人不应该使用它.