How to Print hash key and value in Perl with an example

This short tutorial shows you how to print the hash key and value in Per with examples. Hash is a data type in Perl that contains key and value pairs. hash can be declared with its values as given below

my $emp = {
"one" => 1,
"two" => 2,
"three" => 3,
};

Perl Print Hash Object

Hash Object printed to console in multiple ways. print used to print the values. The key and values are printed in random order, not sorted order.

One way, use a foreach loop.

It prints the key and value pairs of a hash in Perl.

  • used foreach loop, iterated keys in a hash using keys
  • assign the iterated key to a new variable ($key)
  • print the key and value

Here is an example

my $emp = {
"one" => 1,
"two" => 2,
"three" => 3,
};

foreach my $key ( keys %$emp ) {
print $key, " - ", $emp->{$key},"\n";
}
one - 1
three - 3
two - 2

To print only keys, use keys

foreach $key (keys %$emp)
{
print "$key\n";
}

Another way using interpolation syntax

print "@{[ %$emp ]}\n";

Output:

three 3 two 2 one 1

The third way, using the Data::Dumper module that prints stringified versions of data structures.

  • use Data::Dumper in your code
  • the print result of Dumper with hashes
use Data::Dumper;
my $emp = {
"one" => 1,
"two" => 2,
"three" => 3,
};

print Dumper(\%$emp);

Output:

$VAR1 = {
'one' => 1,
'three' => 3,
'two' => 2
};

How do I print a hash key and value in Perl?

To print the key and value pair in Perl, Please follow the below steps

To print the has key in Perl, Please follow the below steps

  • Iterate keys in a hash using the keys function inside a foreach loop
  • Assigned to the $key variable
  • Print the keys using interpolation syntax and value retrieve with the given key.
foreach $key (keys %$emp)
{
print "$key";
}

How do I print a hash key in Perl?

To print the has key in Perl, Please follow the below steps

  • iterate keys in a hash using the keys function inside a foreach loop
  • assigned to the $key variable
  • Print the keys using interpolation syntax
foreach my $key ( keys %$emp ) {
print $key, " - ", $emp->{$key},"\n";
}

How do I print a value in Perl?

To print the has value in Perl, Please follow the below steps.

  • iterate keys in a hashes using the keys function inside a foreach loop
  • assigned to the $key variable
  • Print the values using the given iterate key.
foreach my $key ( keys %$emp ) {
print $emp->{$key},"\n";
}