passing hash in subroutines

107 views Asked by At

I have made a simple perl script for printing hash key/value pairs through subroutine

#!/usr/local/bin/perl

#passing hash to a subroutine

sub printhash{

           my (%hash) = @_;

           foreach my $key (keys %hash){

                    my $value = $hash{$key};

                    print "$key : $value\n ";

          }

}

%hash = {'name' => 'devendra', 'age' => 21};

printhash(%hash);

Expected Output:

name : devendra

age : 21

Ouput:

HASH(0x1be0e78) :

What is wrong with it?

1

There are 1 answers

1
Dondi Michael Stroma On BEST ANSWER

This line

%hash = {'name' => 'devendra', 'age' => 21};

is attempting to assign an anonymous hash reference to a hash. What you really mean is

%hash = ('name' => 'devendra', 'age' => 21);

If you had use strict and use warnings you would have seen the message

Reference found where even-sized list expected

cluing you in to the problem. Always use them!