mnlight has asked for the wisdom of the Perl Monks concerning the following question:

I have created a hash in one subroutine and then pass it to a second subroutine as a reference. I want to loop through the hash and process each element one by one. here is how I tested it. %hash is not recognized.
sub loop_through_hash{ my($hash) = @_; foreach $k (keys %hash){ print "$k => $hash{$k} }#end foreach loop }#end loop_through_hash

Replies are listed 'Best First'.
Re: lopping through a hash passed as a reference
by vek (Prior) on Oct 25, 2002 at 15:38 UTC
    Try this:
    foreach $k (keys %$hash) { print $k, "=>", $hash->{$k}, "\n"; }
    -- vek --
      perfect
Re: lopping through a hash passed as a reference
by VSarkiss (Monsignor) on Oct 25, 2002 at 15:40 UTC

    Very close. Try this instead:

    foreack $k (keys %$hash) { print "$k => $hash->{$k}\n"; print "$k => $$hash{$k}\n"; # equivalent }
    The code you have above is for a hash named %hash, not a reference to a hash contained in a scalar $hash. Notice that in the code above, the sigil preceding the variable is always a $.

    For more info on references in general, take a look at perlref and perlreftut.