How do I build Perl regular expressions dynamically?

后端 未结 6 1499
-上瘾入骨i
-上瘾入骨i 2021-02-08 15:24

I have a Perl script that traverses a directory hierarchy using File::Next::files. It will only return to the script files that end in \".avi\", \".flv\", \".mp3\", \".mp4\", a

6条回答
  •  遥遥无期
    2021-02-08 16:20

    Build it like you would a normal string and then use interpolation at the end to turn it into a compiled regex. Also be careful, you are not escaping . or putting it in a character class, so it means any character (rather than a literal period).

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    my (@ext, $dir, $dirp);
    while () {
        next unless my ($key, $val) = /^ \s* (ext|dirp|dir) \s* = \s* (\S+)$/x;
        push @ext, $val if $key eq 'ext';
        $dir = $val     if $key eq 'dir';
        $dirp = $val    if $key eq 'dirp';
    }
    
    my $re = join "|", @ext;
    $re = qr/[.]($re)$/;
    
    print "$re\n";
    
    while (<>) {
        print /$re/ ? "matched" : "didn't match", "\n";
    }
    
    __DATA__
    ext = avi
    ext = flv
    ext = mp3
    dir = .svn
    dirp= .frames
    

提交回复
热议问题