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

Greetings again Monks, I am having a problem with casting of a HASH that returned to a scalar. Here is a example
#! /usr/bin/perl -w use strict; use MADEUP::MODULE; #Compeletly made up module my $made_up = new MADEUP::MODULE; #A member function of MADEUP::MODLE which returns a hash my $test = $made_up->Return_Hash(); #I know the key "fake_key" and I want to print off of it print $test{fake_key} . "\n";

This will throw a error "Global symbol "%test" requires explicit package name" I understand that there is a differnce between the scalar test "$test" and the hash test "%test" <aka $test{fake_key}> so I try the following to cast it..
print %{$test{fake_key}} . "\n";

I get the same error.. but if I try the following:
my %another= %{$test}; print $another{fake_key} . "\n";
everything works... What is going on??

Replies are listed 'Best First'.
Re: "Casting Question"
by TomDLux (Vicar) on Jun 15, 2003 at 01:27 UTC

    $test is a reference to a hash, so you have to de-reference it, using the arrow:

    print $test->{fake_key} . "\n";

    --
    TTTATCGGTCGTTATATAGATGTTTGCA

      Prefect.. that was all I needed. Thank you :)
Re: "Casting Question"
by theorbtwo (Prior) on Jun 15, 2003 at 03:00 UTC

    Your ideas are correct, your terminology is just off. If the documentation of Some_Method tells you to stuff the result into a scalar, it isn't returning a hash, it's returning a reference to a hash. You need to dereference (not cast) the hash reference into a hash, and then look up the key in a hash.

    %hash = %{$hashref} takes the hashref and dereferences it into a hash, then $hash{key} will look up in that hash. You can also write $hashref->{key}, which dereferences and looks-up in one operation (and is thus much more memory-efficent for large hashes).


    Warning: Unless otherwise stated, code is untested. Do not use without understanding. Code is posted in the hopes it is useful, but without warranty. All copyrights are relinquished into the public domain unless otherwise stated. I am not an angel. I am capable of error, and err on a fairly regular basis. If I made a mistake, please let me know (such as by replying to this node).

Re: "Casting Question"
by The Mad Hatter (Priest) on Jun 15, 2003 at 01:35 UTC
    $test is a hash reference. So to access the values, you need to use the -> notation:
    print $test->{fake_key}, "\n";
    See perldoc perlref for more information concerning references.
Re: "Casting Question"
by mobiGeek (Beadle) on Jun 15, 2003 at 14:58 UTC
    How about this as a dereference of $test:

    print $$test{fake_key} . "\n";