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

I am confused on how to return a hash from a subroutine or if I can even return a hash... My subroutine defines a hash, populates it, and then returns it:
sub savePurpose ... my %hTptPurpose; ... return \%hTptPurpose;
The calling code is:  my $hTableData = savePurpose($szXls);

One of the next things the Perl script tries after calling savePurpose is reference (what I'd like to be) the hash as:  my @aTable = keys %hTableData;

I'm doing something very wrong as the error I get is:  Global symbol "%hTableData" requires explicit package name at...
Can someone help me understand what I am doing wrong with this, keeping in mind that ideally I want to have a hash returned from savePurpose?

Thanks,
Ken

Replies are listed 'Best First'.
Re: Returning a hash?
by GrandFather (Saint) on Aug 24, 2006 at 02:34 UTC

    Very nearly there. Remember you have a hash ref, not a hash, so you need to dereference it:

    my @aTable = keys %$hTableData;

    Welcome to the mad house BTW. Nice first post.

    Update you may find perldsc helpful too.


    DWIM is Perl's answer to Gödel
      Naturally GrandFather is quite correct, BUT, I looked at his response and it took a moment to see that he was de-referencing the hash reference that is being returned.

      For precisely this reason, it is suggested in the book "Perl Best Practices" by thedamian (see p228-229) that when you need to use "prefix dereferencing" such as this, that you used braces around the reference:

      %{$hTableData}
      is more noticeable, and thus readable than:
      %$hTableData
      It makes the dereferencing easier to see in this case, and getting into this habit can make your dereferencing far easier to understand as you meet more complexes cases.

      I must also agree that perldsc is a most useful piece of reading. Welcome to the monastery!

      jdtoronto

      Thank you! I'm off and running with the next challenge. Glad to have found this site.