Well, first of all, your title says "hash of hashes" but what you are working with here is a hash of arrays (actually, hash of anonymous array references).

Rather than walk you through your example code line by line (I assume you must understand some of it and are only really worried about the hash of arrays).

my($login,$gcos) = (split(':',$_))[0,4]; if(exists $USERS{$login}) { push(@{$USERS{$login}},$strip); } else { $USERS{$login} = [$gcos,$strip]; }

The above is the core code that builds your structure. You obtain a login and gcos from a line in a passwd file. Next, you test %USERS to see if that login exists as a key in that hash. If it *doesn't* we assign an anonymous array reference to that key and populate it with the gcos and the current servername stripped from the filename. If the login does exists (we found it in a previous file), then we just push the current server ($strip) onto the array reference that already exists for that key:

push( @{ $USERS{$login} }, $strip );

Here, $USERS{$login} resolves to an array reference and we are de-referencing it: @{ arrayref } in order to push another value onto that array.

In the final section of code, you simply loop over the sorted keys (login ids) of the hash, and print out each login followed by its gcos and the list of servers (contained in the anonymous array) with colon separators. That loop could be simplified to:

foreach my $login (sort keys %USERS) { print NEWFILE join(':', $login, @{$USERS{$login}}), "\n"; }

Hope it helps.


In reply to Re: hash of hashes -newbie question? by Anonymous Monk
in thread hash of hashes -newbie question? by tux242

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.