Bootstrap FreeKB - Perl (Scripting) - Append values to a reference hash that contains an array
Perl (Scripting) - Append values to a reference hash that contains an array

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

Here is how you can create an empty reference hash.

my $hash = {};

 

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

use Data::Dumper;
print Dumper $hash;

 

Which should produce the following.

$VAR1 = {};

 

Let's say you do this.

push @{$hash->{foo}}, { 'name' => 'John Doe', 'department' => 'engineering' };
push @{$hash->{foo}}, { 'name' => 'Jane Doe', 'department' => 'sales' };

 

Now, the foo key contains key value pairs.

$VAR1 = {
          'foo' => [ 
                     {
                       'name' => 'John Doe', 
                       'department' => 'engineering'
                     },
                     {
                       'name' => 'Jane Doe',
                       'department' => 'sales'
                     }
                   ]
        };

 

You can loop through the foo key to print the value associated with the key.

foreach my $foo (@{$hash->{foo}}) {
  print "$foo->{name} \n";
}

 

Which in this example will print the value of the name key.

John Doe
Jane Doe

 


Let's say the hash already contains a key value pair, like this, and you want to append another key value pair at the same place in the hash.

$VAR1 = {
          'foo' => [
                     {
                       'name' => 'John Doe'
                     },
                     {
                       'name' => 'Jane Doe'
                     }
                   ]
        };

 

The following will appended a new key value pair to the block that contains John Doe.

foreach my $foo (@{$hash->{foo}}) {
  if ($foo->{name} eq "John Doe") {
    $foo->{department} = "engineering";  
  }
}

 

Now the hash looks like this.

$VAR1 = {
          'foo' => [
                     {
                       'department' => 'engineering',
                       'name' => 'John Doe'
                     },
                     {
                       'name' => 'Jane Doe'
                     }
                   ]
        };

 




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 5446b9 in the box below so that we can be sure you are a human.