Search code examples
perl

Check Array and Hash is Empty or Not


I have an array and hash. I just want to check whether they both are empty or not.

I found below two methods to check this. Any suggestion which would be more suffice.

#!/usr/bin/perl

use strict; use warnings;
use Data::Dumper;

my @a = qw/a b c/; 
print Dumper(\@a);

my %b = (1 => "Hi");
print Dumper(\%b);

@a = ();
%b = ();

#Method 1
if(!@a && !%b){
    print "Empty\n";
} else {
    print "Not empty\n";
}

#Method 2
if(!scalar @a && !scalar keys %b){
    print "Empty\n";
} else {
    print "Not empty\n";
}

The case here is, either both would be Empty or both would have some values.


Solution

  • For finding whether a hash or array is empty,

    • Hash empty-ness: (%hash) and (keys %hash), when used in a boolean context, are equally optimised internally, and have been since since perl 5.28.0. They both just examine the hash for non-emptiness and evaluate to a true or false value. Prior to that, it was much more complex, and changed across releases, that is to say (keys %hash) may have been faster, but this is no longer a concern.
    • Array empty-ness: @array in scalar context has always been efficient, and will tell you whether the array is empty.