How do I build Perl regular expressions dynamically?

后端 未结 6 1504
-上瘾入骨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:15

    Its reasonably straight forward with File::Find::Rule, just a case of creating the list before hand.

    use strict;
    use warnings;
    use aliased 'File::Find::Rule';
    
    
    # name can do both styles. 
    my @ignoredDirs = (qr/^.svn/,  '*.frames' );
    my @wantExt = qw( *.avi *.flv *.mp3 );
    
    my $finder = Rule->or( 
        Rule->new->directory->name(@ignoredDirs)->prune->discard, 
        Rule->new->file->name(@wantExt)
    );
    
    $finder->start('./');
    
    while( my $file = $finder->match() ){
        # Matching file.
    }
    

    Then its just a case of populating those arrays. ( Note: above code also untested, but will likely work ). I'd generally use YAML for this, it makes life easier.

    use strict;
    use warnings;
    use aliased 'File::Find::Rule';
    use YAML::XS;
    
    my $config = YAML::XS::Load(<<'EOF');
    ---
    ignoredir:
    - !!perl/regexp (?-xism:^.svn)
    - '*.frames'
    want:
    - '*.avi'
    - '*.flv'
    - '*.mp3'
    EOF
    
    my $finder = Rule->or( 
        Rule->new->directory->name(@{ $config->{ignoredir} })->prune->discard, 
        Rule->new->file->name(@{ $config->{want} })
    );
    
    $finder->start('./');
    
    while( my $file = $finder->match() ){
        # Matching file.
    }
    

    Note Using the handy module 'aliased.pm' which imports "File::Find::Rule" for me as "Rule".

    • File::Find::Rule - Alternative interface to File::Find
    • YAML::XS - Perl YAML Serialization using XS and libyaml
    • aliased - Use shorter versions of class names.

提交回复
热议问题