Is there a Perl shortcut to count the number of ma

2019-01-08 09:44发布

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)? Can this be done using a one-liner?

I tried this:

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

I thought that by putting parentheses around $number, I'd force array context, and by the use of scalar, I'd get the count. However, all I get is 1.

8条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-08 10:18

Is the following code a one-liner?

print $string =~ s/\./\./g;
查看更多
我只想做你的唯一
3楼-- · 2019-01-08 10:19
my $count = 0;
my $pos = -1;
while (($pos = index($string, $match, $pos+1)) > -1) {
  $count++;
}

checked with Benchmark, it's pretty fast

查看更多
beautiful°
4楼-- · 2019-01-08 10:19

Friedo's method is: $a = () = $b =~ $c.

But it's possible to simplify this even further to just ($a) = $b =~ $c, like so :

my ($matchcount) = $text =~ s/$findregex/ /gi;

You could thank just wrap this up in a function, getMatchCount(), and not worry about it destroying the passed string.

On the other hand, you can add in a swap, which may be a bit more computation, but does not result in altering the string.

my ($matchcount) = $text =~ s/($findregex)/$1/gi;
查看更多
男人必须洒脱
5楼-- · 2019-01-08 10:21

Try this:


my $string = "one.two.three.four";
my ($number) = scalar( @{[ $string=~/\./gi ]} );

It returns 3 for me. By creating a reference to an array the regular expression is evaluated in list context and the @{..} de-references the array reference.

查看更多
甜甜的少女心
6楼-- · 2019-01-08 10:22

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;
查看更多
看我几分像从前
7楼-- · 2019-01-08 10:22

another way,

my $string = "one.two.three.four";
@s = split /\./,$string;
print scalar @s - 1;
查看更多
登录 后发表回答