如何检查perl中的哈希引用是否为空

前端之家收集整理的这篇文章主要介绍了如何检查perl中的哈希引用是否为空前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要测试,我的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中,键接受引用.然而,这是一个被放弃的实验性功能.一个人不应该使用它.

猜你在找的Perl相关文章