If you really need to type things in manually, try this:
my %hash = ( "Abe" => { "lastname" => "Lincoln", "friends" => { "George" => { "lastname" => "Washington", "wife" => "Martha" } "James" => { "lastname" => "Madison", "wife" => "Dolly" } }, }, "Franklin" => { "lastname" => "Roosevelt", "wife" => "Eleanor" } )
However, if you have some structure, you'll want to stuff these programmatically, instead of retyping all of the keys.

There are several ways to do this. The most direct is to create a sub to navigate the hash for you. The sub will take a hash ref, a value, and a list of keys. The value may itself be a hash(ref), so you can nest these and use loops and so forth.

For example:

#!/your/perl/here use strict; use warnings; use Data::Dumper; sub update_hash { my ($h, $value, @keys) = @_; for my $key (@keys[0..$#keys-1]) { $h = $h->{$key}; } $h->{$keys[-1]} = $value; } # build up a hash from scratch my %hash; update_hash(\%hash, {}, 'one'); update_hash(\%hash, {}, 'one','two'); update_hash(\%hash, 123, 'one','two','three'); # don't have to start at the top update_hash($hash{one}{two},129,'nine'); update_hash($hash{one}{two},{},'zero'); update_hash($hash{one}{two},1208,'zero','eight'); print Dumper(\%hash); __OUTPUT__ $VAR1 = { 'one' => { 'two' => { 'three' => 123, 'zero' => { 'eight' => 1208 }, 'nine' => 129 } } };
The OO approach is really just a group of setters/getters that grok your data structure. If you have a complicated and deeply-nested structure, you might want to do that just for your sanity -- otherwise, it's probably better just to write subs as needed.

-QM
--
Quantum Mechanics: The dreams stuff is made of


In reply to Re: Using multi-level hashes by QM
in thread Using multi-level hashes by carcassonne

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.