Ale*_*lex 3 regex perl grep dynamically-generated
我有以下脚本:
use strict;
use warnings;
my @test = ("a", "b", "c", "a", "ca");
my @res = grep(m#a#, @test);
print (join(", ", @res)."\n");
Run Code Online (Sandbox Code Playgroud)
它应该只返回包含的字符串a.它完美地运作.
问题是我需要能够动态获取这些字符串.我尝试了以下方法:
use strict;
use warnings;
my $match = "a";
my @test = ("a", "b", "c", "a", "ca");
my @res = grep($match, @test);
print (join(", ", @res)."\n");
Run Code Online (Sandbox Code Playgroud)
结果是:
a,b,c,a,ca
我应该怎么做才能grep使用动态变量的数组?
inn*_*naM 11
grep将您提供的LIST中的每个元素作为第二个参数,并检查第一个参数是true还是false.在你的情况下,$match永远是真的,因为它永远是"一个".试试这个:
my @res = grep( m/$match/, @test);
Run Code Online (Sandbox Code Playgroud)
如果您的动态字符串不仅包含字母数字字符,您还应该引用它:
my @res = grep( m/\Q$match/, @test);
Run Code Online (Sandbox Code Playgroud)