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
  • 367,544
  • 15
  • 269
  • 518
Daniel
  • 7,684
  • 7
  • 52
  • 76

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,230
  • 7
  • 27
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
  • 7,684
  • 7
  • 52
  • 76
  • 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