且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

计算一个字符串在另一个字符串中出现的次数(Perl)

更新时间:2021-11-21 22:00:59

您可以捕获字符串,然后对其进行计数.可以通过使用 () 将列表上下文应用于捕获来完成:

You can capture the strings, then count them. It can be done by applying a list context to the capture with ():

my $x = "foo";
my $y = "foo foo foo bar";
my $c = () = $y =~ /$x/g;  # $c is now 3

您还可以捕获到数组并计算数组.相同的原理,不同的技术:

You can also capture to an array and count the array. Same principle, different technique:

my @c = $y =~ /$x/g;
my $count = @c;