Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

How to define and deref hash of hash of hash

by dirtdog (Monk)
on Feb 07, 2017 at 19:24 UTC ( [id://1181331]=perlquestion: print w/replies, xml ) Need Help??

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

Hi Monks,

I'm having trouble finding out how to define a hash of hash of hashes ( I think this is what I want). I just have some hashes of hashes and I realized that I need to pass a parameter to determine which hash of hash i'll be using. Therefore, I thought the hash of hash of hash would be the best solution.

my %Businesses = ( my %teams = ( NFL => { 'JETS' => 1, 'PATRIOTS' => 1, 'GIANTS' => 1 }, MLB => { 'YANKEES' => 1, 'METS' => 1, 'CARDINALS' => 1 }, NBA => { 'SIXERS' => 1, 'CELTICS' => 1, 'LAKERS' => 1 }, ); my %restaurants = ( FASTFOOD => { 'WENDYS' => 1, 'MCDONALDS' => 1, 'BURGER KIN +G' => 1 }, FINEDINING => { 'GRILL 23' => 1, 'CAPITAL GRILL' => 1, 'MO +RTONS' => 1 }, MIDRANGE => { 'OUTBACK' => 1, 'TEXAS ROADHOUSE' => 1, 'CH +ILIS' => 1 }, ); );

If the parameter passed in was "teams" then I would use a for loop to dereference teams, but if the parm was restaurants then I'd dereference those.

CAn someone please let me know how to define the hash of hash of hashes? and then dereference them? Thank you very much for taking the time

Replies are listed 'Best First'.
Re: How to define and deref hash of hash of hash
by kcott (Archbishop) on Feb 07, 2017 at 19:53 UTC

    G'day dirtdog,

    "perldsc - Perl Data Structures Cookbook" should have all the information you need for this task.

    The main problem with the code you show is the declaration and definition of hashes inside the declaration and definition of another hash.

    You can write it like this:

    my %teams = ( ... ); my %restaurants = ( ... ); my %Businesses = ( teams => \%teams, restaurants => \%restaurants, );

    Or like this:

    my $teams = { ... }; my $restaurants = { ... }; my %Businesses = ( teams => $teams, restaurants => $restaurants, );

    Or like this:

    my %Businesses = ( teams => { NFL => { ... }, ... }, restaurants => { FASTFOOD => { ... }, ... }, );

    And various other permutations like those. See the doco I linked to for details.

    You access values like this:

    $Businesses{teams}{NFL}{JETS}

    Again, the doco has details.

    I also note all your values are just "1". That may have some significance but, if it's only to give each key some arbitrary value, you might be better off with arrays:

    ... NFL => [ qw{ JETS PATRIOTS GIANTS } ], ...

    — Ken

      thanks guys...it works like a charm

Re: How to define and deref hash of hash of hash
by stevieb (Canon) on Feb 07, 2017 at 19:40 UTC

    So you want a single hash with all the data? This code shows how, then it goes on to extract all the way down to the teams and their values. Similar code would be used to iterate over the restaurants. It's technically a hash of hashes of hashes.

    use warnings; use strict; my %hoh = ( restaurants => { fast => { mcd => 1, wendys => 1, }, fine => { keg => 1, grill => 1, }, }, teams => { nfl => { pats => 1, falcons => 1, }, nhl => { maple_leafs => 1, flames => 1, }, }, ); my $team_href = $hoh{teams}; for my $league (keys %$team_href){ print "$league\n"; for my $team (keys %{ $team_href->{$league} }){ print "\t$team: $team_href->{$league}{$team}\n"; } } # get one team # ... are the Leafs going to win the cup this year? print "$hoh{teams}->{nhl}{maple_leafs}\n";

    Output:

    nfl falcons: 1 pats: 1 nhl flames: 1 maple_leafs: 1 1
Re: How to define and deref hash of hash of hash
by 1nickt (Canon) on Feb 07, 2017 at 20:32 UTC

    Hi again dirtdog,

    Great advice above from kcott about doing some reading, but you must be feeling frustrated that the advice has come full circle and now you are being told to use arrays instead of hashes! This is because you are describing your sub-tasks and getting advice on each, when what you may really need is advice on how to tackle your overall task. This is sometimes called an XY Problem, as in, your real problem is X but you are asking about Y because you've assumed that's the right approach.

    So, maybe you would like to explain a bit about your overall goal: it may elicit different and more applicable advice. For example, now that I see that you have a configuration section for restaurants as well as sports teams, my advice may have been different: I would have probably suggested using YAML, or an .ini file or some other format that would allow you to maintain your data in discrete sections easily outside your program code.


    The way forward always starts with a minimal test.
      Good comments from 1nickt++. Also good replies from kcott and others.

      If the OP's main goal is just to learn about complicated hash data structures, then I think there is lot's of info in this thread.

      If the OP's goal is to implement some sort of DB application that will "live" and be maintained over time, I think the advice will differ significantly. One point is how add/modify/delete records easily without modifying the actual Perl code. Another consideration might be the difficulty or ease of adding new sections of parameters to existing records. Maybe add NHL for example.

      Some sort of YAML or .ini file for data input is certainly a possibility.There are others.

      What sort of queries do you want to do on this DB that would be useful in an application sense? I have currently no idea. Teams and Restaurants don't seem to have anything to do with each other unless there is some linkage to which ones are near which parks?

      Rather than some complicated HoHoHoH structure, this sounds to me more like an SQlite DB would yield far more flexibly in querying the DB. Just a thought. The combination of a simple DB DQL query coupled with some extra PERL processing can be very powerful.

Re: [OT] How to define and deref hash of hash of hash
by AnomalousMonk (Archbishop) on Feb 07, 2017 at 23:33 UTC

    I think it's interesting that with the correction of one syntactic problem (semicolon statement terminators within the list definition), the OPed code actually works... sorta. At least, it can be made to compile. The data structure desired by dirtdog is absent at the highest level, but at least the structure at lower levels is captured for possible future use.

    What would you need to do to make this appproach work more or less as originally intended? One way:

    I know not of what possible use is this revelation.


    Give a man a fish:  <%-{-{-{-<

Re: How to define and deref hash of hash of hash
by NetWallah (Canon) on Feb 09, 2017 at 02:19 UTC
    I'm a little late to this party - but it was fun to try to make this Object Oriented... Which prints this output:
    --- Teams --- I am a NFL named JETS of type NFL I am a NFL named PATRIOTS of type NFL I am a NFL named GIANTS of type NFL I am a MLB named YANKEES of type MLB I am a MLB named METS of type MLB I am a MLB named CARDINALS of type MLB I am a NBA named SIXERS of type NBA I am a NBA named CELTICS of type NBA I am a NBA named LAKERS of type NBA -- Restaurants -- I am a FASTFOOD named WENDYS of type FASTFOOD I am a FASTFOOD named MCDONALDS of type FASTFOOD I am a FASTFOOD named BURGER of type FASTFOOD I am a FASTFOOD named KING of type FASTFOOD I am a FINEDINING named GRILL 23 of type FINEDINING I am a FINEDINING named CAPITAL GRILL of type FINEDINING I am a FINEDINING named MORTONS of type FINEDINING I am a MIDRANGE named OUTBACK of type MIDRANGE I am a MIDRANGE named TEXAS ROADHOUSE of type MIDRANGE I am a MIDRANGE named CHILIS of type MIDRANGE

            ...it is unhealthy to remain near things that are in the process of blowing up.     man page for WARP, by Larry Wall

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1181331]
Approved by kcott
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (2)
As of 2024-04-25 05:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found