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
whileloop witheach hashvariable in a conditional expression, returns the next pair of items in a hash, and Iterates each pair of elements, printingkeyandvaluepairs. - using for each loop with
each hashvariable - To iterate only keys, use
keyswith a hash variable, that returns an array of keys, iterate using for loop - To iterate only values, use
valueswith 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
forloop to iterate the array, assign each value to newly variable -$key - print
$keyvalue using theprintfunction.
%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
forloop to iterate an array of values, assign each value to newly variable$value - print
$valuevalue using theprintfunction.
%emps = ("1" =>"john" ,"2" =>"andrew","3" =>"trey");
for my $key (keys %emps) {
print "$key\n";
}
Output:
john
andrew
trey
