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

Hey fellow monks,

Please help enlighten me on the behaviour of "%$hash{'output'}" in the snippet of code below

my %hash = ( 'left_fills' => 'Name: a7', 'main_title' => 'Main Area' ); # call do_output # Simplifed to pass just one hash value do_output( output => \%hash, ); sub do_output { my %hash = @_; my $output = $hash{'output'} || 0; # Dumped 1 (OK) print Dumper($output); # Dumped 2 (OK) print Dumper(%$output); # Dumped 3 (OK) print Dumper($hash{'output'}); # Dumped 4 (Script died) print Dumper(%$hash{'output'}); } # print Dumper($output); $VAR1 = { 'left_fills' => 'Name: a7', 'main_title' => 'Main Area' }; # print Dumper(%$output); $VAR1 = 'left_fills'; $VAR2 = 'Name: a7'; $VAR3 = 'main_title'; $VAR4 += 'Main Area'; # print Dumper($hash{'output'}); $VAR1 = { 'left_fills' => 'Name: a7', 'main_title' => 'Main Area' }; # print Dumper(%$hash{'output'}); Error: Global symbol "$hash" requires explicit package named at test.p +l line...
The dumped output of "$hash{'output'}" is identical to that of "$output". But why does dumping "%$hash{'output'}" cause the script to die?

When I did a "ref" of both "$output" and '$hash{'output'}", the result is HASH for both. I'm puzzled why their behaviour isn't exactly identical.

As usual, thanks in advance :)

Replies are listed 'Best First'.
Re: Help with hash reference mystery...
by Roger (Parson) on Dec 21, 2003 at 11:06 UTC
    Your code is not doing what you think it's doing. You should change the code from -
    print Dumper(%$hash{'output'});
    print Dumper(%{$hash{'output'}});
    Because in the original code you were actually dereferencing %{$hash}{'output'}, where the $hash variable was not defined (you defined %hash earlier, but not $hash).

    Add use strict; to the start of your code and you will get a compilation error.

Re: Help with hash reference mystery...
by ysth (Canon) on Dec 21, 2003 at 17:13 UTC
    See Using References in perlref, where it explains that after the % you can have either a simple scalar or a BLOCK containing the hash reference. The error message you got is a clue that it is trying to use $hash, not %hash.
Re: Help with hash reference mystery...
by TomDLux (Vicar) on Dec 21, 2003 at 16:07 UTC

    I'm using 5.8.0; even without use strict;, I got a syntax error on line 28.