๐Ÿ“˜ Count words using Perl 6

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s