Hi bisimen,

the solution suggested by toolic uses regular expressions to cut the string into segments of $length (2, in this case) letters. Regular expressions are a very powerful feature of Perl that you really need to learn at some point.

However, assuming you don't know regular expressions yet, this is another way you could do it, which might be easier for you to understand:

my $str = "BEBEBEHUHUHUJJFAFALL"; my $length = 2; my $index = 0; my %cnt; # hash to store the counters while (1) { # infinite loop my $substring = substr $str, $index, $length; # getting a subst +ring of $length length, starting at offet $index (initially 0) last if length($substring) < $length; # exiting the inf +inite loop if we are at the end of the string $cnt{$substring}++; # increasing the +counter for the substring $index += $length; # increasing the +offset by $length }
This creates the following counters in the %cnt hash:
'BE' => 3 'FA' => 2 'HU' => 3 'JJ' => 1 'LL' => 1
Note that this is not the way I would do it, but it is hopefully easier to understand for you, and one of Perl's favorite mottoes is: TIMTOWTDI, i.e. there is more than one way to do it.

Update: Using unpack would most probably be more efficient. Here I only wanted to show a possible process step by step.


In reply to Re^3: Counting words by Laurent_R
in thread Counting words by bisimen

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.