FreeKB - Loop through hash values
Perl - Loop through hash values

If you are not familiar with hash in Perl, check out our getting started article.

Let's say you've created %hash that contains the following key:value pairs.

Key Value
Name Jeremy
ID 123456
Occupation Engineer

 

The following foreach loop will print the value associated with each key in %hash.

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

 

Which will print each value.

Jeremy Canfield
123456
Engineer

 

Or like this.

foreach my $value (values %hash) {
    print $value;
}

 

Will print the values.

Jeremy Canfield
123456
Engineer

 

 

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

 

Which will print each key.

name
id
occupation

 

Or like this, to loop through both the keys and the values.

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

 

Will print the following.

name -> Jeremy Canfield
id -> 123456
occupation -> Engineer

 



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




Comments