How do I build Perl regular expressions dynamically?

后端 未结 6 1515
-上瘾入骨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条回答
  •  猫巷女王i
    2021-02-08 16:08

    Lets say that you use Config::General for you config-file and that it contains these lines:

    
        extensions    avi flv mp3 mp4 wmv
        unwanted      frames svn
    
    

    You could then use it like so (see the Config::General for more):

    my $conf = Config::General->new('/path/to/myapp.conf')->getall();
    my $extension_string = $conf{'MyApp'}{'extensions'};
    
    my @extensions = split m{ }, $extension_string;
    
    # Some sanity checks maybe...
    
    my $regex_builder = join '|', @extensions;
    
    $regex_builder = '.(' . $regex_builder . ')$';
    
    my $regex = qr/$regex_builder/;
    
    if($file =~ m{$regex}) {
        # Do something.
    }
    
    
    my $uw_regex_builder = '.(' . join ('|', split (m{ }, $conf{'MyApp'}{'unwanted'})) . ')$';
    my $unwanted_regex = qr/$uw_regex_builder/;
    
    if(File::Next::dir !~ m{$unwanted_regex}) {
        # Do something. (Note that this does not enforce /^.svn$/. You
        # will need some kind of agreed syntax in your conf-file for that.
    }
    

    (This is completely untested.)

提交回复
热议问题