user110084 user110084 - 1 month ago 11
Perl Question

Perl: passing hash by ref using rule1

I am still unclear about why by ref portion is showing undefined value for

%Q
and
$_
uninitialized. I have been looking through
perlreftut
and still unable to see what I have done wrong. Passing the hash as a flat array has no issue.

Doing it by ref with
testRef(\%mkPara)
passes a scalar hash reference to the subroutine, right? So, does
my %Q = %{$_}
not turn it back into a hash?

use strict;
use diagnostics;
use warnings;

my %mkPara = ('aa'=>2,'bb'=>3,'cc'=>4,'dd'=>5);

sub testFlat
{
my %P = @_;
print "$P{'aa'}, $P{'bb'}, ", $P{'cc'}*$P{'dd'}, "\n";
}

sub testRef
{
my %Q = %{$_}; #can't use an undefined value as HASH reference
#print $_->{'aa'}, "\n";#Use of uninitialized value
print $Q{'aa'},"\n";
}

#testFlat(%mkPara);
testRef(\%mkPara);

Answer

When you use arguments in a function call (\%mkPara in your case), you can access them through @_ array inside the function.

Here, you pass a single argument to the function : \%mkPara, which you can then access by accessing the first element of @_ by using $_[0].

$_ is the default variable for some builtin functions/operators (print, m//, s///, chomp and a lot more). Usually seen in while or for loops. But in your code, you have no reason to use it (you are never setting it to anything, so it's still set to undef, hence the error "Can't use an undefined value as a HASH reference".

So your function should actually be :

sub testRef
{
    my %Q = %{$_[0]}; # instead of %{$_}
    print  $_[0]->{'aa'}, "\n"; # instead of $_->{'aa'}
    print $Q{'aa'},"\n";
}

If needed, you can find more about functions on perlsub.

Comments