Bootstrap FreeKB - Perl (Scripting) - Determine if a key is defined in a hash
Perl (Scripting) - Determine if a key is defined in a hash

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 = { };

 

Let's say you create an empty hash.

my %hash = ();

 

Dumper can be used to display the structure of the hash.

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

 

Which will return the following.

$VAR1 = {};

 

The following if statement will return "is defined".

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

 

Since %hash contains no keys, the following will return "does not exist".

AVOID TROUBLE

Do not wrap the hash reference in double quotes, such as "$hash{foo}", as this might cause the evaluation to fail.

if ( $hash{foo} ) {
  print "exists \n";
}
else {
  print "does not exist \n";
}

 

Let's create an empty key.

$hash{foo} = "";

 

Dumper will return the following.

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

 

The following will return "is empty".

if ( $hash{foo} ) {
  print "\$hash{foo} is not empty\n";
}
else {
  print "\$hash{foo} is empty\n";
}

 

Let's define a string element.

$hash{foo} = "bar";

 

Dumper will return the following.

$VAR1 = {
           'foo' => 'bar'
        };

 

The following if statement will return "is not empty".

if ( $hash{foo} ) {
  print "\$hash{foo} is not empty\n";
}

 

Let's define a boolean element.

$hash{foo} = 0;

 

The following if statement will return "is empty", meaning that boolean 0 is interpreted as empty.

if ( $hash{foo} ) {
  print "\$hash{foo} is not empty\n";
}
else {
  print "\$hash{foo} is empty\n";
}

 

Let's define a boolean element greater than 0.

$hash{foo} = 1;

 

The following if statement will return "is not empty", meaning that a boolean greater than 0 is interpreted as not empty.

if ( $hash{foo} ) {
  print "\$hash{foo} is not empty\n";
}
else {
  print "\$hash{foo} is empty\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 994e4c in the box below so that we can be sure you are a human.