Re: Hashes of Hashes



On 12/28/06, Jason Malburg <jcmalburg@xxxxxxxxx> wrote:
Hi,
I'm working on a complex data structure with hashes of hashes and
hashes of arrays and I noticed a weird behavior I was hoping someone
could explain. Here's a sample:

$Data{US17}{1}{GROUP} = "STRING";
$Data{US17}{1}{GROUP}{.001} = 5;
$Data{US17}{1}{GROUP}{.002} = 6;
$Data{US17}{1}{GROUP}{.003} = 7;
print "group = $Data{US17}{1}{GROUP}\n";
for my $time (keys %{$Data{US17}{1}{GROUP}}){
print "time = $time $Data{US17}{1}{GROUP}{$time}\n";
}

The output is:
group = STRING
time = 0.002 6
time = 0.003 7
time = 0.001 5

If I swap the order of the declarations, then all of the keys for the
hash under 'GROUP' are wiped out. For example:
$Data{US17}{1}{GROUP}{.001} = 5;
$Data{US17}{1}{GROUP}{.002} = 6;
$Data{US17}{1}{GROUP}{.003} = 7;
$Data{US17}{1}{GROUP} = "STRING";

only produces:
group = STRING

Is this expected behavior? Am I getting lucky in the first instance
with bad syntax that just happens to do what I want?

Thanks in advance,
Jason

Hi Jason,

If you want to make hashes of hashes or any other complex data
structure like that, you probably want to be using references. Perl
flattens arrays/hashes contained in another array/hash. That is, (1,
2, 3, 4, (1, 2, 3)) is the same as (1, 2, 3, 4, 1, 2, 3). Take a look
at perldoc perldsc and/or perldoc perlreftut. You might also want to
use the Data::Dumper module to take see what your data structures
actually look like (so you know you've done it correctly). If you add
this to your code:

use Data::Dumper;
....
print Dumper(%Data);

You'll probably see that your data structure isn't what you intended.
Hope that helps.

- Jen
.



Relevant Pages

  • Re: Identifying common elements from multiple hashes
    ... > I am trying to write a program that will compare multiple hashes. ... That's why the posting guidelines encourage ... the program needs to identify the values of 'x' that appear in ... This works (but it may not mimic your data structure, ...
    (comp.lang.perl.misc)
  • Re: Find element in array of hashes
    ... country" - in that case I'd say all of us three live in the same country. ... which i tried to explain my writing: ... a data structure for your data and put it into a Hash indexed by file name, ... explain the structre of each Array of hashes. ...
    (comp.lang.ruby)
  • Re: Hash questions
    ... I use a the OO capabilities of Perl to define a data structure using a ... hash of hashes - this unfortunately implies that the resulting data ... not the structure of the hash (i.e. it should be impossible to add any ...
    (comp.lang.perl.misc)
  • References
    ... I am trying to create this data structure as below: ... Is it an array of ... hashes that is being stored in a scalar? ... single record,, but I am having trouble understanding how I ...
    (perl.beginners)