For Programmers: Free Programming Magazines  


Home > Archive > PERL Miscellaneous > April 2007 > Passing a single hash to a sub









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Passing a single hash to a sub
darius

2007-04-27, 7:02 pm

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.
Paul Lalli

2007-04-27, 7:02 pm

On Apr 27, 11:17 am, darius <n...@here.invalid> 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

darius

2007-04-27, 7:02 pm

Paul Lalli <mritty@gmail.com> wrote in
news:1177684678.694915.190460@c18g2000prb.googlegroups.com...

> 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
>



Thank you :)
Sadfasdfsd

2007-04-29, 6:48 am

http://Britney-Spears-jerking.info/...hp?movie=148803
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com