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

Hi, How do i grep a text file for lines that contain multiple items? for example: instead of: grep /him|her/ @arr for 'or' greps. i want lines in the array that contain both 'him' and 'her' Thanks. Max

Replies are listed 'Best First'.
Re: 'and' greps
by FunkyMonk (Bishop) on Jul 29, 2009 at 17:39 UTC
      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?

        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

        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