Bootstrap FreeKB - Perl (Scripting) - Loop through values in a hash
Perl (Scripting) - Loop through values in a hash

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

In this example, the foo key contains a value of Hello and the bar key contains a value of World.

my %hash = ( 'foo' => 'Hello', 'bar' => 'World' );

 

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

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

 

Which should produce the following.

$VAR1 = {
          'foo' => 'Hello',
          'bar' => 'World'
        };

 

Looping through the hash keys . . .

foreach my $key (keys %hash ) {
  print "$hash{$key} \n";
}

 

. . . can be used to print the values.

Hello
World

 




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