Reputation: 85
There is such a hash:
$hash = { Apple => 'red', Lemon => 'yellow', Carrot => 'orange' }
How do you know if there is at least one key in the hash?
Upvotes: 2
Views: 186
Reputation: 482
Above mentioned methods are good. But if you want more information about hash you can use https://metacpan.org/pod/Hash::Util module.
bucket_info method : Return a set of basic information about a hash.
Code
use strict;
use warnings;
use Hash::Util qw(bucket_info);
my $hash = { Apple => 'red', Lemon => 'yellow', Carrot => 'orange' };
my $empty_hash = {};
my ($keys, $buckets, $used, @length_counts)= bucket_info($hash);
print "\n Number of keys $keys in the hash \n";
print "\n Number of buckets $buckets in the hash \n";
print "\n Number of used buckets $used in the hash \n";
((bucket_info($hash))[0]) ? print "\n Not Empty hash" : print "\n Empty hash";
((bucket_info($empty_hash))[0]) ? print "\n Not Empty hash" : print "\n Empty hash";
output
Number of keys 3 in the hash
Number of buckets 8 in the hash
Number of used buckets 2 in the hash
Not Empty hash
Empty hash
Upvotes: 1
Reputation: 385685
Simply using the hash in scalar context will suffice.
if (%hash) { # Or %$hash in your case.
say "Not empty";
} else {
say "Empty";
}
%hash
vs keys(%hash)
keys(%hash)
in scalar context: Returns the number of elements.%hash
in scalar context (≥5.26): Returns the number of elements.%hash
in scalar context (<5.26): Returns whether the hash is empty or not.So, no matter the version, you can always simply use %hash
in scalar context to check if a hash is empty. keys(%hash)
can be used to achieve the same result, but %hash
in boolean context (e.g. if (%hash)
) has been faster than an equivalent use of keys(%hash)
since 5.12.
So, no matter the version, you can always simply use keys(%hash)
in scalar context to get the number of elements in the hash. You can also use %hash
in scalar context in newer versions.
Upvotes: 3
Reputation: 50637
Hash returns non-false value in scalar context when populated, or key - value pairs in list context.
You can simply check if it is not empty with,
if (%$hash)...
Upvotes: 1
Reputation: 3222
You can decide the hash key size using: scalar keys(%hash)
. Based on the size your check can be done below:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my %hash = (
Apple => 'red',
Lemon => 'yellow',
Carrot => 'orange'
);
print Dumper(\%hash);
print "Size:".scalar keys(%hash)."\n";
if(scalar keys(%hash) > 0){
print "Hash size is greater than 1\n";
} else {
print "Hash size is zero\n";
}
Upvotes: 1