Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re^2: Counting words

by bisimen (Acolyte)
on Nov 04, 2017 at 18:09 UTC ( [id://1202758]=note: print w/replies, xml ) Need Help??


in reply to Re: Counting words
in thread Counting words

This works!

Bit confused about how tho... But, thanks lad.

Replies are listed 'Best First'.
Re^3: Counting words
by Laurent_R (Canon) on Nov 05, 2017 at 00:17 UTC
    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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1202758]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (6)
As of 2024-04-19 10:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found