GREP获取包含特定字符串的所有字符串

3
我有以下的脚本:
 use strict;
 use warnings;

 my @test = ("a", "b", "c", "a", "ca");
 my @res = grep(m#a#, @test);

 print (join(", ", @res)."\n");

它应该只返回包含a的字符串。它完美地工作。

问题是我需要能够动态获取这些字符串。 我尝试了以下方法:

 use strict;
 use warnings;

 my $match = "a";
 my @test = ("a", "b", "c", "a", "ca");
 my @res = grep($match, @test);

 print (join(", ", @res)."\n");

结果是:

a、b、c、a、ca

我应该怎么做才能使用动态变量来使用 grep 数组?
2个回答

11

grep 函数接受你提供的列表作为第二个参数,并检查第一个参数是 true 还是 false。在您的情况下,$match 将始终为 true,因为它始终是 "a"。请尝试以下代码:

my @res = grep( m/$match/, @test);
如果您的动态字符串中可能包含除字母数字字符以外的其他字符,则还应该对其进行引用:
my @res = grep( m/\Q$match/, @test);

4
我想您需要:

我认为您需要:

my @res = grep { $_ =~ $match } @test;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接