本文介绍了是否有一个Perl的快捷方式来计算在一个字符串匹配的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有:

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

我应该如何与环境发挥拿到模式找到了匹配(3)的次数?可以这样使用一班轮做?

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?

我试过这样:

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

我认为,通过把周围 $号括号,我会强迫阵列上下文,通过使用标量,我会得到计数。但是,我得到的是 1

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.

推荐答案

这让正则表达式本身在标量的背景下,这是不是你想要的。相反,放在列表上下文正则表达式(以获得匹配的数量),并把的的成标量环境。

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;

这篇关于是否有一个Perl的快捷方式来计算在一个字符串匹配的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 06:53