rabbit55 has asked for the wisdom of the Perl Monks concerning the following question:

Novice kowtows before the masters three times. Would like to use grep to extract the subset of an array. The array contains many lines beginning with sequences like QAB_ QKC_ QGE_ etc. the subset must contain all lines which do not begin with the sequence QKC_. How to proceed?
  • Comment on how to find all lines which do not start with something

Replies are listed 'Best First'.
Re: how to find all lines which do not start with something
by ishnid (Monk) on Sep 16, 2004 at 14:54 UTC
    TIMTOWTDI - without regexp:
    my @new = grep { index $_, 'QKC_' } @orig;
    index returns 0 (i.e. false) if the string starts with 'QKC_', so those lines will not be returned by grep

      This is a nice trick, but I guess it will have to search through the entire line, not only the beginning, so it can be a bit slow.

      Possibbilities are:

      my @new = grep { rindex $_, 'QKC_', 0 } @orig;
      or simply
      my @new = grep { substr($_, 0, 4) ne 'QKC_' } @orig;
      Tiny note: if you're favoring index over a regexp because of speed, then you should also prefer to use grep in comma form instead of with a BLOCK:
      my @new = grep index($_, 'QKC_'), @orig;
Re: how to find all lines which do not start with something
by Anonymous Monk on Sep 16, 2004 at 14:21 UTC
    @weeded_out = grep(!/^QKC_/, @original_array);
Re: how to find all lines which do not start with something
by Anonymous Monk on Sep 16, 2004 at 14:22 UTC
    untested:

    without grep:
    foreach my $line (@lines) { next if $line =~ /^QKC_/; #do something with $line }
    with grep:
    @subset = grep(/^QKC_/, @lines);
      Your grep does the opposite of what it should. Add a '!' in front of /^QKC_/.