How to check if a hash link is empty in perl

I need to check if my hashref contains 0 elements. I used this code:

$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";

It works well with perl 5.16, but does not work with 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.
+5
source share
4 answers

If you use

%hash

for hash you should use

%{ $hash }

for reference so this

keys %{ $self->{href} }

Note. In some versions, Perl keysaccepts a link. However, it was an experimental function that was abandoned. It should not be used.

+12
source

Using links with built-in type functions keysis only supported in new Perls. For maximum compatibility, you must first dereference it:

print "size of hashref:  " . keys( %{ $self->{href} } ) . ".\n";
+2
source

:

print "size of hashref: ", keys %{ $self->{href} }, "\n";

TIMTOWTDI, , - , keys:

print "undefined" unless %{ $self->{href} };
+2

, , :

scalar %h

%h ? "yup" : "nope"

scalar keys %haccomplishes the same goal by counting keys in %h, but it’s better to ask what you really want to know.

In any case, it %his a hash, not a hashref. (Although some versions of Perl allow hashref as an argument for keys.) Given an expression EXPRthat evaluates hashref, you get the corresponding hash by saying %{ EXPR }. Putting this along with your sample code, we get

print "size of hashref:  " . keys( %{ $self->{href} } ) . ".\n";
print "hash " . (%{ $self->{href} } ? "does" : "does not") . " contain elements\n";
+1
source

All Articles