Skip to content
Blog Perl: Function to print a HASH completely

Perl: Function to print a HASH completely

Below is a perl function that i wrote to print a HASH completely. What i mean by ‘completely’ is that it will expand all hashes and arrays found within the given HASH.

sub print_hash {
  my ($hash,$str)  = @_;
  while( my ($k, $v) = each %{$hash}) {
    print $str."$k  =>  $v\n";
    if( $v =~ /hash/i ) {
      print_hash($v,$str."\t\t");
    }
    if( $v =~ /array/i ) {
      print "$str\t\t".join(", ",@{$v})."\n";
    }
  }
}

Below is a sample script which shows the use of the above function.

#!/usr/bin/perl
#-------------------------------------------------#
#  File:    printhash.pl                          #
#  Author:  Dipin Krishna [email protected]   #
#-------------------------------------------------#

sub print_hash {
  my ($hash,$str)  = @_;
  while( my ($k, $v) = each %{$hash}) {
    print $str."$k  =>  $v\n";
    if( $v =~ /hash/i ) {
      print_hash($v,$str."\t\t");
    }
    if( $v =~ /array/i ) {
      print "$str\t\t".join(", ",@{$v})."\n";
    }
  }
}
# Initialize two arrays
@array1 = (3,4,5,67,8);
@array2 = ('a','d','g','h','j','l');

# Below is a hash whose has an array in it.
%hash2 = ('key1' => 21, 'key2' => 22, 'key3' => 23, 'array2' => \@array2);

# Below is a hash who has a hash in it.
%hash1 = ('key1' => 11, 'key2' => 12, 'hash2' => \%hash2);

# Now lets declare a hash which has an array and
# a hash(which contains an hash(with an array) in it) in it.
%hash = ( 'key1' => 'value1',
  'key2' => 'value2',
  'key3' => 'value3',
  'array1' => \@array1,
  'hash1' => \%hash1
);

# Now print the final HASH
print_hash(\%hash);

Ouput:

array1  =>      ARRAY(0x9632c08)
                3, 4, 5, 67, 8
key2    =>      value2
key1    =>      value1
hash1   =>      HASH(0x9632ef8)
                hash2   =>      HASH(0x9632e38)
                                key2    =>      22
                                key1    =>      21
                                array2  =>      ARRAY(0x9632d98)
                                                a, d, g, h, j, l
                                key3    =>      23
                key2    =>      12
                key1    =>      11
key3    =>      value3

Hoping, it will be useful.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.