繁体   English   中英

如何使用Perl的智能匹配功能一次匹配许多模式?

[英]How do I use Perl's smart matching to match many patterns at once?

我试图按照以下示例在以下代码中使用智能匹配,但是失败了(没有过滤掉任何内容)。 如何在此处使用智能匹配一次匹配多个正则表达式?

my $regexes_to_filter_a = ("tmp", "temp", "del")
my @organism_dirs = (); # this will hold final list of dirs to processs

my @subdirs = File::Find::Rule->directory->maxdepth(1)->in($root_dir);
foreach my $subdir (@subdirs) {
    my $filter = 0;

    # IMPROVE: can do smart matching here
    foreach my $regex ( @{$regexes_to_filter_a} ) {
        if ( basename($subdir) =~ $regex ) {
            $filter = 1; # filter out this dir
            last;
        }
    }

    unless ($filter) {
        push @organism_dirs, $subdir;
    }
}

您不需要在这里进行智能匹配。 就像您拥有它一样,~~在右侧带有单个正则表达式,在左侧带有字符串也可能是=〜。 你想做什么?

对于您的比赛,您有两种方法。 如果要将字符串用作模式,则需要使用match运算符:

 basename($subdir) =~ m/$regex/

如果您不想像现在那样使用match运算符,则需要一个regex对象:

 my $regexes_to_filter_a = (qr/tmp/, qr/temp/, qr/del/);

我想您可以一次匹配所有正则表达式。 请注意,如果要将maxdepth设置为1,则实际上不需要File :: Find :: Rule。 如果您不想遍历目录结构,请不要使用旨在遍历目录结构的模块:

my $regexes_to_filter_a = (qr/tmp/, qr/temp/, qr/del/);
my @organism_dirs = ();

foreach my $subdir ( glob( '*' ) ) {
    next unless -d $subdir;
    unless (basename($subdir) ~~ @regexes_to_filter_a) {
        push @organism_dirs, $subdir;
            } 
        }

我认为所有这些工作太多了。 如果要排除已知的静态目录名称(因此,不包括模式),请使用哈希:

my %ignore = map { $_, 1 } qw( tmp temp del );

my @organism_dirs = 
    grep { ! exists $ignore{ basename($_) } } 
    glob( "$rootdir/*" );

如果您确实要使用智能匹配:

my %ignore = map { $_, 1 } qw( tmp temp del );

my @organism_dirs = 
    grep { basename($_) ~~ %ignore } 
    glob( "$rootdir/*" );

这是您示例的未经测试的快速更改:

my @regexes_to_filter_a = (qr/^tmp$/, qr/^temp/, qr/del/);
my @organism_dirs = (); # this will hold final list of dirs to processs

my @subdirs = File::Find::Rule->directory->maxdepth(1)->in($root_dir);
foreach my $subdir (@subdirs) {

    unless (basename($subdir) ~~ @regexes_to_filter_a) {
        push @organism_dirs, $subdir;
    }
}

关键更改是:

我)应该是@array = (...list...); $array_ref = [...list...];

my @regexes_to_filter_a = ("tmp", "temp", "del");

ii)并更改为使用智能匹配 下面检查@regexes_to_filter_a数组中( ~~ )中的@regexes_to_filter_a basename($subdir) 因此,无需遍历数组并进行单独的正则表达式检查。

unless (basename($subdir) ~~ @regexes_to_filter_a) { ... }

/ I3az /

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM