SPUG: Reference to a hash

Martin, Asa asa.martin at attws.com
Thu Mar 21 22:57:25 CST 2002

Jim describes exactly what was happening. Changing \%hash to {%hash} made it
work correctly. 

Thank you very much.


-----Original Message-----
From: Jim Flanagan [mailto:jimfl at tensegrity.net]
Sent: Thursday, March 21, 2002 8:17 PM
To: Martin, Asa; spug-list at pm.org
Subject: Re: SPUG: Reference to a hash

  What may be happening to you is that you're assigning \%hash to the HoH,
  then undef-ing %hash later on. This is similar to the common references
  mistake is something along the lines of

      while (my $line = <STDIN>) {
        %hash = my_func($line);
        $things{$key} = \%hash;

  Only to find later that the hash references all contain the same data!
  It's because they're all references to the same hash, the one that was
  constructed in the last iteration through the loop.

  What you really want is an anonymous hashref, rather than a reference to
  a specific named hash. One way to get that is the loop that you have
  below. Another way is to just say

      $HoH{$key}{$heading} = {%hash};

  This creates a new, anonymous hash with the same keys/values as %hash.

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
      Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
  Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
 For daily traffic, use spug-list for LIST ;  for weekly, spug-list-digest
     Seattle Perl Users Group (SPUG) Home Page: http://seattleperl.org

More information about the spug-list mailing list