FreeKB - Perl (Scripting) Hash Array (determine if hash array defined)
Perl (Scripting) - Hash Array (determine if hash array 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 = [ ];


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 array. In this example, the foo key is an 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' => []


Now the following if statement should return "is defined".

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


Here is how you would determine if %hash contains a key named "foo".

foreach my $key ( keys %hash ) {
  if ( $key eq "foo" ) {
    print "The foo key is defined \n";
  else {
    print "The foo key is not defined \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 67550 in the box below so that we can be sure you are a human.


Web design by yours truely - me, myself, and I   |   |