I need to test, whether 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 fails 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.
From perldoc perldata: If you evaluate a hash in scalar context, it returns false if the hash is empty. If there are any key/value pairs, it returns true; more precisely, the value returned is a string consisting of the number of used buckets and the number of allocated buckets, separated by a slash.
Similar to the array, Perl hash can also be referenced by placing the '\' character in front of the hash. The general form of referencing a hash is shown below. %author = ( 'name' => "Harsha", 'designation' => "Manager" ); $hash_ref = \%author; This can be de-referenced to access the values as shown below.
Empty values in a Hash: Generally, you can't assign empty values to the key of the hash. But in Perl, there is an alternative to provide empty values to Hashes. By using undef function. “undef” can be assigned to new or existing key based on the user's need.
You need to use the \ operator to take a reference to a plural data type (array or hash) before you can store it into a single slot of either. But in the example code given, if referenced, each would be the same hash.
If you'd use
%hash
for a hash, you'd use
%{ $hash }
for a reference, so it's
keys %{ $self->{href} }
Note: In some versions of Perl, keys
accepts a reference. However, this was an experimental feature that was abandoned. One shouldn't use it.
To find out if a hash has elements, you just use it in scalar context:
scalar %h
or
%h ? "yup" : "nope"
scalar keys %h
accomplishes the same purpose by counting the keys in %h
, but it's better to ask for what you actually want to know.
Either way, however, %h
is a hash and not a hashref. (Though some versions of Perl do tolerate a hashref as an argument to keys
.) Given an expression EXPR
that evaluates to a hashref, you get at the corresponding hash by saying %{ EXPR }
. Putting this together with your sample code, we get
print "size of hashref: " . keys( %{ $self->{href} } ) . ".\n";
print "hash " . (%{ $self->{href} } ? "does" : "does not") . " contain elements\n";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With