如何在 Perl 中检查多个模式匹配 [英] How to check for multiple pattern matching in Perl
本文介绍了如何在 Perl 中检查多个模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么方法可以避免将其用于多个模式检查吗?
Is there a way I can avoid using this for multiple pattern checks?
我可以撕掉一个数组中的所有模式并检查它是否与模式数组中的任何模式匹配吗?请考虑我有超过 20 个模式字符串的情况.
Can I tore all the patterns in an array and check if it matches any pattern in the pattern array? Please consider the case when I have more than 20 pattern strings.
if( ($_=~ /.*\.so$/)
|| ($_=~ /.*_mdb\.v$/)
|| ($_=~ /.*daidir/)
|| ($_=~ /\.__solver_cache__/)
|| ($_=~ /csrc/)
|| ($_=~ /csrc\.vmc/)
|| ($_=~ /gensimv/)
){
...
}
推荐答案
如果您可以使用 Perl 5.10 版,那么有一种非常简单的方法可以做到这一点.只需使用新的智能匹配 (~~) 运算符.
If you can use Perl version 5.10, then there is a really easy way to do that. Just use the new smart match (~~) operator.
use warnings;
use strict;
use 5.10.1;
my @matches = (
qr/.*\.so$/,
qr/.*_mdb\.v$/,
qr/.*daidir/,
qr/\.__solver_cache__/,
qr/csrc/,
qr/csrc\.vmc/,
qr/gensimv/,
);
if( $_ ~~ @matches ){
...
}
如果你不能使用 Perl 5.10,那么我会使用 List::MoreUtils::任何.
If you can't use Perl 5.10, then I would use List::MoreUtils::any.
use warnings;
use strict;
use List::MoreUtils qw'any';
my @matches = (
# same as above
);
my $test = $_; # copy to a named variable
if( any { $test =~ $_ } @matches ){
...
}
这篇关于如何在 Perl 中检查多个模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文