How can I efficiently match many different regex patterns in Perl?

前端 未结 8 2138
礼貌的吻别
礼貌的吻别 2020-12-18 07:52

I have a growing list of regular expressions that I am using to parse through log files searching for \"interesting\" error and debug statements. I\'m currently breaking th

8条回答
  •  旧时难觅i
    2020-12-18 08:20

    This is handled easily with Perl 5.10

    use strict;
    use warnings;
    use 5.10.1;
    
    my @matches = (
      qr'Failed in routing out',
      qr'Agent .+ failed',
      qr'Record Not Exist in DB'
    );
    
    # ...
    
    sub parse{
      my($filename) = @_;
    
      open my $file, '<', $filename;
    
      while( my $line = <$file> ){
        chomp $line;
    
        # you could use given/when
        given( $line ){
          when( @matches ){
            #...
          }
        }
    
        # or smartmatch
        if( $line ~~ @matches ){
          # ...
        }
      }
    }
    

    You could use the new Smart-Match operator ~~.

    if( $line ~~ @matches ){ ... }
    

    Or you can use given/when. Which performs the same as using the Smart-Match operator.

    given( $line ){
      when( @matches ){
        #...
      }
    }
    

提交回复
热议问题