8

In Perl 5 we can write

my @things = $text =~ /thing/g;

And $things in scalar context is number of non-overlapping occurrences of substring thing in string $text.

How to do this in Perl 6?

ikegami
  • 343,984
  • 15
  • 249
  • 495
Daniel
  • 6,020
  • 5
  • 38
  • 65

2 Answers2

7

You can do it like this:

my $text = 'thingthingthing'
my @things = $text ~~ m:g/thing/;
say +@things; # 3

~~ matches the left side against the right side, m:g makes the test return a List[Match] containing all the results.

Kaiepi
  • 3,170
  • 5
  • 26
  • Yw. I like to clean up comments so I've deleted my prior one. If you delete your thank you comment then I'll also delete this one. – raiph Apr 02 '18 at 06:31
5

I found solution on RosettaCode.

http://rosettacode.org/wiki/Count_occurrences_of_a_substring#Perl_6

say '01001011'.comb(/1/).elems;     #prints 4
Daniel
  • 6,020
  • 5
  • 38
  • 65
  • 7
    Note that currently you can make this go a lot faster if the regular expression just consists of a string: `say '01001011'.comb("1").elems` (which is about 15x faster because it doesn't use the regular expression engine and the many, many `Match` object creations) – Elizabeth Mattijsen Apr 01 '18 at 11:55
  • 4
    @ElizabethMattijsen Changed the RosettaCode example to use a Str as the argument, with a note that it being basically the same as a regex. – Brad Gilbert Apr 01 '18 at 14:33