http://qs1969.pair.com?node_id=1202757


in reply to Counting words

Your array only has a single element. I'll show how you would split each big string into smaller strings of 2 letters each using a regular expression. Each 2-letter word is stored in a hash.
use warnings; use strict; my $length = 2; my $str = "BEBEBEHUHUHUJJFAFALL"; my %cnt; while ($str =~ /(.{$length})/g) { $cnt{$1}++; } print "Found:\n"; print "$_ $cnt{$_}\n" for sort keys %cnt; __END__ Found: BE 3 FA 2 HU 3 JJ 1 LL 1

Replies are listed 'Best First'.
Re^2: Counting words
by bisimen (Acolyte) on Nov 04, 2017 at 18:09 UTC

    This works!

    Bit confused about how tho... But, thanks lad.
      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.