FreeKB - Perl Array of Hashes
Perl - Array of Hashes

Let's say you have similar blocks of data, like this.

{
 'name_key' => 'Jeremy',
 'id_key'   => '111111'
},
{
 'name_key' => 'Winston',
 'id_key'   => '222222'
}

 

Start by creating an empty array.

my @array = ();

 

Manually populate the array of hashes.

@array = (
          {
            'name_key' => "Jeremy",
            'id_key'   => "111111"
          },
          {
            'name_key' => "Winston",
            'id_key;   => "222222"
          }
  );

 

Or, use push.

push @array, { 'name_key' => "Jeremy",  'id_key' => "111111" }; 
push @array, { 'name_key' => "Winston", 'id_key' => "222222" }; 

 

You could use Dumper to display the structure.

use Data::Dumper;
print Dumper \@array;

 

Which will show that the data is in the expected structure.

$VAR1 = [
          {
            'name_key' => 'Jeremy',
            'id_key' => '111111'
          },
          {
            'name_key' => 'Winston',
            'id_key' => '222222'
          }
        ];

 

You can now loop through the array and print the value associated with a key.

foreach my $line (@array) {
  print $line->{name_key};
}

 



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 71430 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   |