in reply to Passing hashes by reference

I noticed that you created a copy of the hash, and modified the copy of the hash, not the original hash. If you want to modify the original hash, you need to do something like below...

sub loader{ # loads values into hash.. my $tail = shift; my $h_ref = shift; print 'In sub:'.Dumper($h_ref); $h_ref->{'one'}='thing_'.$tail; $h_ref->{'two'}='thong_'.$tail; print 'After add:'.Dumper($h_ref); }
Your code my %h_ref = %{+shift}; created a local copy of the hash.

Replies are listed 'Best First'.
Re: Re: Passing hashes by reference
by wolis (Scribe) on Dec 02, 2003 at 04:35 UTC
    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
      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' };

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