in reply to Re: Passing hashes by reference
in thread Passing hashes by reference

Such a quick response, thanks.

I noticed that you used ->:

$h_ref->{'one'}='thing_'.$tail;
Am I right in assuming the -> is the key to the whole thing.

Is it the only way of referencing the hash?

And do lists and scalars need this or is it just the complicated old hash that does?

___ /\__\ "What is the world coming to?" \/__/ www.wolispace.com

Replies are listed 'Best First'.
Re: Re: Re: Passing hashes by reference
by Roger (Parson) on Dec 02, 2003 at 04:50 UTC
    Corrent. '->' dereferences a reference to a hash. Note that I do not have to explicitly tell Perl that I am dereferencing a reference to a hash, Perl will work it out.

    I have constructed the following example to show how to dereference a hash in a sub and modify its contents.

    use strict; use Data::Dumper; my %hash = qw/ A 1 B 2 /; print 'Before sub:'.Dumper(\%hash); modify_hash(\%hash); print 'After sub:'.Dumper(\%hash); sub modify_hash{ my $h_ref = shift; $h_ref->{C} = '3'; $h_ref->{D} = '4'; %{$h_ref}->{E} = '5'; # this is what it's doing $$h_ref{F} = '6'; # you could do this too }
    And the output is -
    Before sub:$VAR1 = { 'A' => '1', 'B' => '2' }; After sub:$VAR1 = { 'F' => '6', 'A' => '1', 'B' => '2', 'C' => '3', 'D' => '4', 'E' => '5' };
Re: Re: Re: Passing hashes by reference
by jweed (Chaplain) on Dec 02, 2003 at 04:48 UTC

    Yes, the -> is key. Without it, the lhs would be interpreted as $h_ref{'one'}, ie an element of the hash %h_ref.

    Though this is convenient, it isn't the only way to do it. You may use the notation $$href{'one'}, but that's just ugly. The same notation can be use with arrays (not the same thing as a list!) like this: $my_array->[1]



    Who is Kayser Söze?
Re: Re: Re: Passing hashes by reference
by exussum0 (Vicar) on Dec 02, 2003 at 12:37 UTC
    You can also use this form.
    $hash = { a=>1 }; ${$hash}{b}=2; print ${$hash}{a}; print ${$hash}{b};
    I prefer this form, though I'm sure it's the unpopular way. :)

    Play that funky music white boy..