FreeKB - Perl (Scripting) Hash (determine if hash key is defined)
Perl (Scripting) - Hash (determine if hash key is defined)

In Perl, there are 3 different kinds of hashes.

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

 

Let's say you create an empty regular 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";
}

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |