Bootstrap FreeKB - Perl (Scripting) - Determine if an array in a hash is empty
Perl (Scripting) - Determine if an array in a hash is empty

Updated:   |  Perl (Scripting) articles

In Perl, there are 2 different kinds of hashes.

  • A hash, which is defined by the % and ( ) characters - %hash = ( );
  • A reference hash, which is defined with the $ and { } characters - $hash = { };

 

The following if statement will return "is defined" when the hash array named %hash is defined.

if ( %hash ) {
  print "The regular hash named \%hash is defined\n";
}

 

If the hash array named %hash has not been defined, something like this will be returned.

Global symbol "%hash" requires explicit package name

 

Let's say you create a regular hash that contains an empty array. In this example, the foo key contain an empty array, as indicated by the [ ] characters.

my %hash = ( 'foo' => [] );

 

Dumper can be used to display the structure.

use Data::Dumper;
print Dumper \%hash;

 

Which should return the following.

$VAR1 = {
          'foo' => []
        };

 

Here is how you would show that the foo key contains an empty array.

if ( @{$hash{foo}} == 0 ) {
  print "The foo key contains an empty array \n";
}

 

And here is how you would show that the foo key does not contain an empty array.

if ( @{$hash{foo}} != 0 ) {
  print "The foo key does NOT contain an empty array \n";
}



Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 370dbc in the box below so that we can be sure you are a human.