Boetsie:

For a trivial solution, you can use recursion: Your degenerate/simple cases is when you have a single string and a hash reference--you can simply:

++$$hr{$string};

If you have more than one string, though, you can instead get the hash referenced by the first string, and then call the function recursively with the new hash reference and the array of strings less the first one.

So you could end up with (untested):

my %hash; my @tests = ( [ 'string1', 'string2', 'string3', 'string4' ], [ 'string3', 'string4' ], [ 'string1', 'string2', 'string3' ], ); for my $t (@tests) { my $hr = \%hash; my @strings = @$t; increment($hr, @strings); } sub increment { my ($hr, @strings) = @_; if (@strings == 1) { # simple case ++$$hr{$strings[0]}; } else { # Peel the first string from the list my $first_string = shift @strings; # Get the associated hash reference $hr = $$hr{$first_string}; # Call ourself... increment($hr, @strings); } }

Of course, there are a few hairy areas in there. What do you do if your first list of strings is 'bar', 'foo' and then your next list is 'bar', 'foo', 'baz'? After the first list, the second level of the hash contains your incremented value instead of a hash reference. How will you handle that? That's just one of the subtleties you'll have to deal with. (On reviewing the test cases you provided, you actually get that sort of situation! Hint: perldoc -f ref.)

Have fun!

...roboticus

When your only tool is a hammer, all problems look like your thumb.


In reply to Re: variable number of hash of hashes by roboticus
in thread variable number of hash of hashes by Boetsie

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.