Re: Passing a single hash to a sub



On Apr 27, 11:17 am, darius <n...@xxxxxxxxxxxx> wrote:
Hi

This looks correct, yet isn't

%h = ();
test('hello','there',%h);
print( $h{'hello'});

sub test
{
my ($k,$v,%h) = @_;
$h{$k} = $v;

}

perl says unse of uninit. value in print.

I tried passing by ref

%h = ();
test('hello','there',\%h);
print( $h{'hello'});

sub test
{
my ($k,$v,$ref) = @_;
my (%h) = %$ref;
$h{$k} = $v;

}

doesn't work either.

sorry for the newbie Q, but I'm stumped.

In both cases, you're making copies of the hash. The keys/values are
copied over into a brand new hash that has nothing at all to do with
the old one.

You want to directly modify the existing hash. To do this, like your
second case, you need to use a reference. But then you can't create a
new hash using the values of the old hash. You have to directly
modify the hash that $ref references:

$ref->{$k} = $v;

For more info, please see:
perldoc perlreftut

Paul Lalli

.



Relevant Pages