SPUG: Reference to a hash

Jim Flanagan jimfl at tensegrity.net
Thu Mar 21 22:16:35 CST 2002


  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.

--On Thursday, March 21, 2002 5:41 PM -0800 "Martin, Asa" 
<asa.martin at attws.com> wrote:

     > I have a data structure, Hash of Hashes. Most of the entries are
     > single values. Some are however other hashes. I use $key as a
     > numeric number incremented for each hash with each key having
     > different headings. For example..
     >
     > $HoH{$key}{$heading1} = $value1;
     > $HoH{$key}{$heading2} = $value2;
     > ....
     >
     > For the times when $value is not a scalar, I populate a hash of
     > values. I then tried to associate that hash as a value like so:
     >
     > $HoH{$key}{$heading} = \%hash;
     >
     > For some reason this did not work. When I went to access it as
     > %{HoH{$key}{$heading}} it did not contain the original data but was
     > empty. So I had to do this to populate it.
     >
     > for (keys %hash) {
     >     $HoH{$key}{$heading}{$_} = $hash{$_};
     > }
     >
     > Any ideas as to what's going on here? I'm sure I'm missing something
     > obvious (certainly wouldn't be the first time).
     >
     > Thanks,
     >
     > Asa C Martin

-- 
::jim flanagan

  http://jimfl.tensegrity.net
  mailto:jimfl%40t%65ns%65gr%69ty.n%65t


 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     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