Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for multiple pattern matching in Perl

Is there a way I can avoid using this for multiple pattern checks?

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/)
){
  ...
}
like image 315
Arovit Avatar asked Mar 02 '11 13:03

Arovit


2 Answers

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 ){
  ...
}

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 ){
  ...
}
like image 158
Brad Gilbert Avatar answered Nov 15 '22 05:11

Brad Gilbert


Another pre-Perl 5.10 option is Regexp::Assemble, which will take a list of patterns and combine them into a single regex that will test all of the original conditions at once.

like image 32
Dave Sherohman Avatar answered Nov 15 '22 06:11

Dave Sherohman