Anonymity provides you with the ability to create very complex data structures. Say you're stuck with a flat ASCII file that really ought to be a database. You parse the lines, and create a named hash to represent your database. The values can now be array or hash references, so that the rest of the data in your record can be organized how you want it -- but how do you get as many arrays and hashes as you need, on the fly?

Anonymous hashes and arrays, of course.

Even better is a situation I just came across where I needed to build an array for each key, but I didn't know when I got to a key if I'd seen it before. So I just use

# Rebuild the canonical list, but now we lose duplicates foreach my $name (keys %byname) { # First instance of the id number needs an array ref if (! $final{$byname{$name}}) { $final{$byname{$name}} = [ $name ]; } # Additional instances get pushed onto the existing # (anonymous) array else { push @{$final{$byname{$name}}}, $name; } }
This is a cool example because the %byname hash was built from a hash that had array refs as values, and the arrays were filled with names, possibly duplicates. When I built the %byname hash, the duplicates get eaten up since they "point" to the same key, so that the %final hash looks a bit like the hash %byname was built from, but all the duplicate names are gone.

I will be the first to admit that I need to master the

 -> 
notation to make my code more readable and intuitive, though :)


In reply to RE: RE: Anonymity by snax
in thread Anonymity by snax

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.