Wednesday, January 2, 2013

Perl - How to print a hash?

How to print the contents of a hash? Let us see in this article the different options to print a hash.

1. Using foreach and keys:

use warnings;
use strict;


my %h1=(Jan => 31, Feb => 28, Mar => 31);

foreach my $key (keys%h1) {
        print "$key => $h1{$key} ";
   Using the keys function, the keys are generated and processed in a loop. In every iteration, the key and its corresponding value is printed using the $key variable which holds the key.

On running this program, it gives:
Mar => 31
Feb => 28
Jan => 31
2. Without using temporary variable:
my %h1=(Jan => 31, Feb => 28, Mar => 31);

foreach (keys%h1) {
     print "$_ => $h1{$_} ";
  The foreach can also be written without the temprary variable. In this case, Perl will assign the key to the Perl Special variable, $_ .

3. Using the each function:
my %h1=(Jan => 31, Feb => 28, Mar => 31);

while (my ($k,$v)=each%h1) {
        print "$k => $v ";
   each is a Perl built-in function which gives a key-value pair for a given hash which are collected in the variables $k and $v. The while loop is run till all the key-value pairs are processsed after which each cannot retrieve any more.

4. Using the each function in scalar context:
my %h1=(Jan => 31, Feb => 28, Mar => 31);

while (my $k=each%h1) {
        print "$k => $h1{$k} ";
  each function returns value depending on the context. If the values is collected in list context, returns key-value pair, else returns key alone in scalar context.

5. Using the Dumper function:
use Data::Dumper;

my %h1=(Jan => 31, Feb => 28, Mar => 31);

print Dumper \%h1;
The output printed for the above will be :
$VAR1 = {
          'Mar' => 31,
          'Feb' => 28,
          'Jan' => 31
  Dumper function is one of the most important functions in Perl to print array, hashes, references, etc. Dumper prints the entire stuff in a properly structured format which makes it easily understandable. The point to be noted is that the reference should be provided to the Dumper function always.

No comments:

Post a Comment