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

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 "%hash is not defined".

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

 

Let's create an empty key.

$hash{foo} = "";

 

Dumper will return the following.

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

 

The following if statement will now return "%hash is defined". This shows that a hash becomes defined once the hash contains a key, even if the key is empty.

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

 

However, the following if statement 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 6a200 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   |