Algorithms, Perl, Perl Tutorials, Tutorials

Various ways to print the content of hash in Perl

Sending
User Rating 5 (2 votes)

What is the various ways to print the contents of a hash?

Hash in Perl is nothing but an associative array i.e. Each key is associate with its value and can be displayed using either key or value. It is preferred over simpler array because instead of printing value based on index number, you can print by using key.
Ex:

$hash{'key'} = 'value';<br />

We will discuss Hash fundamentals in another tutorial where I will explain everything which is required to understand hash clearly with some examples. Let’s see here, how we can display the contents of hash. We assume we have a hash defined as %hash = (some key value pairs);

Method 1: Printing Hash contents using hash variable name directly (Doesn’t look good)

print %hash,"\n"; # try print %hash."\n";

Method 2: Printing a hash using array

Using temporary array

my @arr = %hash;
print "@arr\n";

or using Anonymous array reference

print "@{ [ %hash ] } \n";

 

Method 3: Printing a Hash using each function and while loop

We used while loop here because each function returns a list consisting key and value.

while ( ( $key, $value ) = each %hash ){
  print "Key:$key has its value as: $value\n";
}

Method 4: Printing a Hash using keys function

We can do that in many way and two frequent ways are either using foreach or map function over each keys.

  • Using map

print map { "Key: $_ has Value:$hash{$_}\n" } keys %hash;
  • Using foreach (most common method)

foreach my $key ( keys %hash ){
  print "Key:$key has value: $hash{'$key'}\n";
}

Method 5: Using Data::Dumper

You must include use Data::Dumper;  in your code before using Dumper method.

print Dumper \%hash;

Note: I didn’t show the way to access hash reference. It is the most simple form of accessing hash elements. Later we would cover some other ways to display contents when we will cover hash reference 🙂

 

 

Share your Thoughts