FreeKB - Perl (Scripting) Hash Array (append key value pairs)
Perl (Scripting) - Hash Array (append key value pairs)

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 = [ ];

 

In this example, the foo key in the hash is an array, as indicated by the [ ] characters. The foo key is empty (contains no values).

my %hash = ( 'foo' => [] );

 

You can count the elements.

my $count = @{$hash{employees_key}};
print "\$count = $count \n";

 

Which will return 0, since the foo key is empty.

$count = 0

 

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

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

 

Which should produce the following.

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

 

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' => [ 
                     {
                       'foo' => 'John 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' => [ 
                     {
                       'name' => 'John Doe', 
                       'department' => 'engineering'
                     }
                   ]
        };

 

 



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 608a3 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   |