my @array = (
'There were \d* errors that occurred',
'Your system exploded because \.*',
);
my $error = 'There were 22 errors that occurred';
if (grep(/$error/, @array)) {
print 'That error is ok, continue...';
} else {
die;
}
Run Code Online (Sandbox Code Playgroud)
在perl中是否有任何方法可以将完整字符串与包含正则表达式的字符串进行比较?就像在这个例子中我想要两个$ error ='发生了22个错误'和$ error ='发生了12341235个错误'与一种"模板"字符串进行比较并返回一个布尔值火柴.我想,使用grep可能是不可能的.
也许像这样的东西实际上有效:
my @s = ('there were \d* errors');
print _error_checker(@s, 'there were 10 errors');
sub _error_checker {
my (@acceptable_errors, $text) = @_;
foreach my $error (@acceptable_errors) {
if ($text =~ /$error/) {
return 1;
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你很接近,你只需要在grep中反转你的测试.
my @ok_errors = (
'There were \d* errors that occurred',
'Your system exploded because \.*',
);
my $errmsg = 'There were 22 errors that occurred';
if (grep {$errmsg =~ /$_/} @ok_errors) {
print 'That error is ok, continue...';
} else {
die;
}
Run Code Online (Sandbox Code Playgroud)
此外,您可以使用缓存正则表达式 qr{}
my @ok_errors = (
qr{There were \d* errors that occurred},
qr{Your system exploded because \.*},
);
my $errmsg = 'There were 22 errors that occurred';
if (grep {$errmsg =~ $_} @ok_errors) {
print 'That error is ok, continue...';
} else {
die;
}
Run Code Online (Sandbox Code Playgroud)