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.
CodePudding user response:
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.
CodePudding user response:
Array
Use @a
in scalar context.
Examples:
say @a ? "not empty" : "empty";
@a
or die( "At least one value is required" );
my $num_elements = @a;
Hash
Use %h
or keys( %h )
in scalar context.
If the code will be run on older versions of Perl, you want keys( %hash )
because %h
was inefficient before 5.26.
Examples:
say %h ? "not empty" : "empty"; # Slower before 5.26
say keys( %h ) ? "not empty" : "empty";
%h # Slower before 5.26
or die( "At least one element is required" );
keys( %h )
or die( "At least one element is required" );
my $has_elements = %h; # Slower before 5.26
my $num_elements = %h; # 5.26
my $num_elements = keys( %h );
Note that !@a
and !scalar @a
are identical since !
already imposes a scalar context. The same goes for !scalar keys %b
and !keys %b
.