How to Iterate key and values in Hash Perl script with an example

This tutorial explains how to pass command line arguments to a Perl script file with code examples. Many ways to iterate hash objects in Perl.

  • using a while loop with each hash variable in a conditional expression, returns the next pair of items in a hash, and Iterates each pair of elements, printingkey and value pairs.
  • using for each loop with each hash variable
  • To iterate only keys, use keys with a hash variable, that returns an array of keys, iterate using for loop
  • To iterate only values, use values with hash variable, that returns an array of values, iterate using for loop

How to iterate keys and values in Perl Hash

  • using while loop

each hashvarible returns the next key and value of elements of the hash object.

each hash

The While loop iterates until the next element is not found.

Finally, print the key and value of a hash variable.

%h = ("1" =>"john" ,"2" =>"andrew","3" =>"trey");
while(my($k, $v) = each %h){
    print "$k - $v\n";
}

Output:

1 - john
2 - andrew
3 - trey
  • using foreach loop

key hashvarible returns an array of keys of a hash variable.

key hash

foreach loop iterates an array of elements. For each iteration, prints the key and value using hash{key} syntax.

Finally, print the key and value of a hash variable.

%emps = ("1" =>"john" ,"2" =>"andrew","3" =>"trey");
foreach my $k (keys %emps)
{
    print "$k - $emps{$k}\n";
}

Output:

1 - john
2 - andrew
3 - trey

How to iterate and print keys in Perl Hash?

To print only the keys of a hash, Please follow the below steps.

  • Initialize a hash table using hash literal syntax.
  • First, Call keys hashvariable, which returns an array of keys.
  • use the for loop to iterate the array, assign each value to newly variable - $key
  • print $key value using the print function.
%emps = ("1" =>"john" ,"2" =>"andrew","3" =>"trey");
for my $key (keys %emps) {
  print "$key\n";
}

Output:

1
2
3

How to iterate and print values in Perl Hash?

To print only values of a hash, Please follow the below steps.

  • Initialize a hash variable using hash literal syntax.
  • First, Call values hashvariable, which returns an array of values.
  • use for loop to iterate an array of values, assign each value to newly variable $value
  • print $value value using the print function.
%emps = ("1" =>"john" ,"2" =>"andrew","3" =>"trey");
for my $key (keys %emps) {
  print "$key\n";
}

Output:

john
andrew
trey