Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Re^3: Counting words

by Laurent_R (Canon)
on Nov 05, 2017 at 00:17 UTC ( #1202770=note: print w/replies, xml ) Need Help??

in reply to Re^2: Counting words
in thread Counting words

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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1202770]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (4)
As of 2018-07-18 19:02 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (393 votes). Check out past polls.