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

I am stumped populating a hash of hashes which consists of complex data. I am parsing a file which consists of multiple records in a custom format. I only want to capture 5 fields. Three fields are simple which I populate as key=> value pairs (i.e. $hash{$counter}{'variable'} = variable). The other two fields are repeatable (i.e. http://www.google.com, http://www.greenpeace.com, http://www.perl.com, etc). So I am pushing these fields as push @{$fields},$url. The problem I am experiencing is that when I use this strategy to pupulate my hoh, the array is counted rather than stored as a reference value. I use $hash{$counter}{'url'} = push @{$fields},$url. I tried using eval {push @{$fields},$url}, but same results. I am sure I am missing something very simple here. Can you folks guide me in the right direction? What's the best way to capture the value of an array reference in a hash of hash key? Thanks for all your help. Still trying to sort this out...

Replies are listed 'Best First'.
Re: Complex Hash of Hashes Data Structure
by NetWallah (Canon) on Jun 02, 2006 at 00:10 UTC
    The syntax you are looking for is :
    push @{$hash{$counter}{url}}, "http://my.url.com";
    If you are trying to count unique URLs for each $counter, try:
    $hash{$counter}{url}{$CurrentURL}++; # Auto-vivify and count

         "For every complex problem, there is a simple answer ... and it is wrong." --H.L. Mencken

      The syntax of pushing the value onto the hash key did the trick. I used data::Dumper and here is a sample of a record:
      '46' => { 'doc' => 'J 29.9/6:', 'url' => [ 'http://www.myurl.com', 'http://www.mysecondurl.com' ], 'item' => { '2' => undef }, 'title' => 'Sourcebook of criminal justice statist +ics' },
      What took me more than a day, you guys resolved in less than a few minutes. Thank you all. I really appreciate it.
Re: Complex Hash of Hashes Data Structure
by davido (Cardinal) on Jun 02, 2006 at 00:13 UTC

    This line is definitiely problematic:

    $hash{$counter}{'url'} = push @{$fields},$url

    ...because push has a return value of the number of elements in @{$fields} after $url is pushed. I'm not exactly sure what you're after, but I know that you're misusing push, and getting unexpected results.

    I suspect you're after something more like this:

    push @{ $hash{$counter}{url} }, $url;

    Dave

Re: Complex Hash of Hashes Data Structure
by GrandFather (Saint) on Jun 02, 2006 at 00:09 UTC

    Try providing a little code and a little sample data. The following template may help:

    use strict; use warnings; use Data::Dump::Streamer; my %uberHash; while (<DATA>) { #parse data and populate uberhash } Dump (\%uberHash); __DATA__ your sample data here (about 5 shortish lines ought be enough)

    and show the result you would like to see.


    DWIM is Perl's answer to Gödel