Perl:grep匹配时不应该匹配

时间:2014-04-23 06:27:31

标签: regex perl

sub process_ignore{
    my $col_ref = shift;
    my $ignore_ref = shift;
    foreach ( @{$ignore_ref} ) {
        if ( grep( /^$_$/, @{$col_ref})) {
            print "Will ignore column: $_\n" if $debug;     
        } else {
            print "Will not ignore column: $_\n because not a valid column" if $debug;
        }
    }

    if ($debug) {
        foreach my $val ( @{$col_ref} ) {
            print "$val\n";
        }
    }
}

&process_ignore(\@cols, \@ignores)

-
@cols有A_ID,STATUS,STIME
@ignores有a_id,sdd

输出:
将忽略列:a_id
将忽略列:sdd
援助 STATUS
STIME

我不确定为什么它不应该进入匹配的if块。
@cols中没有sdd

另外,grep会忽略大小写吗?即a_id vs A_ID?

2 个答案:

答案 0 :(得分:1)

您将$col_ref的元素与自己匹配,因为grep暂时胜过$_的值

    if ( grep( /^$_$/, @{$col_ref})) {

您可以通过引入查找哈希来提高此功能的效率,

sub process_ignore{
    my $col_ref = shift;
    my $ignore_ref = shift;

    my %seen;
    @seen{ @$ignore_ref } = ();
    foreach ( @$col_ref ) {
        if (exists $seen{$_}) {
            print "Will ignore column: $_\n" if $debug;     
        } else {
            print "Will not ignore column: $_\n because not a valid column" if $debug;
        }
    }
}

答案 1 :(得分:1)

替换:

foreach ( @{$ignore_ref} ) { if ( grep( /^$_$/, @{$col_ref})) {

到(至少):

foreach my $ignore ( @{$ignore_ref} ) { if ( grep( /^$ignore$/, @{$col_ref})) {

甚至(如果没有必要使用regexp):

foreach my $ignore ( @{$ignore_ref} ) { if ( grep {$_ eq $ignore} @{$col_ref} ) {