THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
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.
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.each hash
variablekeys
with a hash variable, that returns an array of keys, iterate using for loopvalues
with hash variable, that returns an array of values, iterate using for loopeach 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
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
To print only the keys of a hash, Please follow the below steps.
keys hashvariable
, which returns an array of keys.for
loop to iterate the array, assign each value to newly variable - $key
$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
To print only values of a hash, Please follow the below steps.
values hashvariable
, which returns an array of values.for
loop to iterate an array of values, assign each value to newly variable $value
$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
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts