user2763829
user2763829

Reputation: 801

perl loop hash using each keyword on foreach loop

I tried to loop through a hash using each on a for each loop. Looks like the $k $v is not updated. Can anyone explain?

%hash = (a=>5,b=>6);
foreach( my ($k,$v) = each %hash){
    print "\neach loop : $k $v\n";
}

output :
each loop : a 5
each loop : a 5

Upvotes: 0

Views: 684

Answers (3)

LeoNerd
LeoNerd

Reputation: 8532

foreach takes a list of values, and executes its loop body once per value, assigning some variable ($_ if otherwise unspecified) each time:

foreach ( 1, 2, 3 ) {
  print "The value is $_\n";
}

In your case, you gave it a list of two things, being the first key and value taken from the hash. Additionally, you also assigned those two new variables, $key and $value to be the key and value. Thus, your loop executed twice, with those variables remaining constant throughout.

A better way to iterate keys and values from a hash is to iterate on the list of keys, taking a value each time:

foreach my $key ( keys %hash ) {
  my $value = $hash{$key};
  ...
}

Alternatively, you might enjoy the pairs function from List::Util version 1.39:

foreach my $pair ( pairs %hash ) {
   my $key   = $pair->key;
   my $value = $pair->value;
}

Upvotes: 4

user3243135
user3243135

Reputation: 820

You need to do while instead of foreach:

my %hash = (a=>5,b=>6);
while( my ($k,$v) = each %hash){
    print "\neach loop : $k $v\n";
}

However, each() has gotachas that you need to be aware of, so I prefer just using keys instead, like this:

for my $k (keys %hash) { my $v = $hash{$k};  }

Upvotes: 1

Chankey Pathak
Chankey Pathak

Reputation: 21676

Use the while loop.

#!/usr/bin/perl
use strict;
use warnings;
my %hash = (a=>5,b=>6);
while (my ($key, $value) = each %hash) {
          print "Key is $key, value is $value\n";
}

Demo

Also see: Is perl's each function worth using?

Upvotes: 3

Related Questions