📘 Count words using Perl 6

📘 Count words using Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.

Count the number of words in a text.

Before solving the task, let us assume that by words we mean here a sequence of alphanumeric characters, including the underscore symbol.

Here is the solution:

my $text = prompt('Text> ');
say $text.comb(/\w+/).elems;

Try it on a few test inputs:

$perl6 countwords.pl 
Text> Hello, World;

The program uses regexes for extracting words using the \w character class and the combstring method that returns a sequence of the words:


The + quantifier allows a repetition of \w, so it matches the whole word. 

Alternatively, a more traditional match with a regex may be used:

$text ~~ m:g/(\w+)/;
say $/.elems;

Parentheses in the regex capture the word, and the :g adverb applies it a few times until all the words are found. The $/ variable (called the match object) keeps all the matched substrings, and the elems method returns the number of elements in it.

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code