Is there a Perl shortcut to count the number of matches in a string?

前端 未结 9 884
生来不讨喜
生来不讨喜 2020-12-01 00:54

Suppose I have:

my $string = \"one.two.three.four\";

How should I play with context to get the number of times the pattern found a match (3

9条回答
  •  鱼传尺愫
    2020-12-01 01:33

    That puts the regex itself in scalar context, which isn't what you want. Instead, put the regex in list context (to get the number of matches) and put that into scalar context.

     my $number = () = $string =~ /\./gi;
    

提交回复
热议问题