Using iteration for populating the hash is fairly simple, but recursion is tidy for dumping the structure:

#!/usr/bin/perl use strict; use warnings; my %hash; while (<DATA>) { my $parent = \%hash; chomp; for my $str (split ',') { $parent = $parent->{$str} ||= {}; $parent->{count}++ } } dumpHash (\%hash, ''); sub dumpHash { my ($hash, $indent) = @_; for my $child (sort keys %$hash) { next if $child eq 'count'; print "$indent$child $hash->{$child}{count}\n"; dumpHash ($hash->{$child}, "$indent "); } } __DATA__ string1,string2,string3,string4 string3,string4 string1,string2,string3 string1,string3,string5

Prints:

string1 3 string2 2 string3 2 string4 1 string3 1 string5 1 string3 1 string4 1

Note that you need to keep a count and a hash (ref) of any child nodes for each parent node. Incrementing a hashref will not lead to a happy life!

True laziness is hard work

In reply to Re: variable number of hash of hashes by GrandFather
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.