in reply to variable number of hash of hashes
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.
|
|---|