in reply to Re: 'and' greps
in thread 'and' greps

One more question. Can i do it dynamically? Meaning grepping for lines that contain all the items in an array. Almost like grepping one array with another, finding lines in arr2 that contains every element in arr1. is that possible?

Replies are listed 'Best First'.
Re^3: 'and' greps
by philipbailey (Curate) on Jul 29, 2009 at 19:29 UTC

    Something like this should work for you:

    #!/usr/bin/perl use warnings; use strict; my @to_match = qw/his her theirs/; START: for my $line (<DATA>) { for my $item (@to_match) { next START unless $line =~ /$item/; } print $line; } __DATA__ his her theirs asdf his her something else this shouldn't match either

Re^3: 'and' greps
by Marshall (Canon) on Jul 30, 2009 at 12:02 UTC
    If you want to compare arrays there are more efficient ways. But to expand on grep{} in a list context, you can put anything you want inside the grep. If the *last line* in the grep is "true" then input is passed to the output.

    Here is a simple example where what is in the grep{} has nothing to do with the input list...an odd/even flip-flopper. Perl grep can do some very cool things that command line grep can't!

    #!/usr/bin/perl -w use strict; my @test = qw (a b c d e f); my $is_even_flag =1; my @odd_tests = grep {$is_even_flag ^= 1; }@test; print "@odd_tests"; #prints b d f