【问题标题】:Perl: Using grep to delete element of array that match a pattern and do not match anotherPerl:使用 grep 删除与模式匹配但不匹配另一个的数组元素
【发布时间】:2014-05-27 10:02:27
【问题描述】:

我有两个包含以下元素的数组:

my @type = ("man", "boy"); 
my @array = (
          "=stat_man", 
          "=stat_boy" 
          "=ref_g_man",  
          "=g_man", 
          "=g_boy", 
          "=happy_man" ,
          "an element", 
          "another element", 
          "=ref_g_boy"
);

作为一个选项,我只想删除 @array 中包含字符串 'stat' 的行,在另一种情况下,我希望它删除不包含字符串的元素'stat',但包含@type 的元素。于是我写了:

foreach my $type (@type) {
    if(condition) {
        @array = grep {! /stat_$type/}@array;     #works. Deletes elements with 'stat'
    }
    else {
        @array = grep {! /(?!stat)_$type/}@array; #sort of...works
    }
}

好的,现在我卡住了。在 else 中,所有包含 $type 且不包含 'stat' 的元素都将被删除。没关系。 但我想要的是第二个 grep 只删除包含 $type 的元素,不包含 'stat' 并且 not 删除前缀由超过 1 个单词组成的元素。

例如,我想要

"=g_man" , "=g_boy" and "=happy_man" deleted, but not "=ref_g_man" and "=ref_g_boy".  

如果我在第二个 grep 中的 (?!stat) 前面添加任何内容,则它不起作用。

基本上,我不知道如何将第三个条件添加到 grep。

【问题讨论】:

    标签: arrays regex perl grep


    【解决方案1】:

    您试图同时解析和过滤,这会变得很混乱。最好分开做。我将把解析部分留给你,你更了解数据。你可能会想出类似的东西。

    my @stuff = (
        { type => "man", stat => 1 },
        { type => "boy", stat => 1 },
        { type => "man", g    => 1, ref => 1 },
        ...
    );
    

    然后过滤变得更容易。

    for my $type (@types) {
        @stuff = grep { $_->{type} eq $type } @stuff;
    }
    

    我想你应该可以从这里走。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 2013-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多