in reply to Online GREP problem

...so it would find any combination of the two words

You could also do it without grep and temp files:

#!/usr/bin/perl my @words = qw(we love); while (<DATA>) { # all search words must appear, but order is irrelevant my $found = 0; for my $search (@words) { $found = /\Q$search/i; last unless $found; } print if $found; } __DATA__ foo we love bar love we foo bar foo love bar we foo we bar love foo bar

Output:

foo we love bar love we foo bar foo love bar we

In place of the special DATA handle I'm using here for demo purposes, you'd use the file handle you've opened to your input file, i.e.

open my $fh, "<", $DataIn or die "Couldn't open '$DataIn': $!"; while (<$fh>) { ...

Replies are listed 'Best First'.
Re^2: Online GREP problem
by gfausel (Initiate) on Apr 05, 2010 at 21:13 UTC
    Interestingly enough, the file is never opened. There are 4 grep calls before my altered one. Any reason that the grep line is enclosed in ``? here are the previous calls.
    if($aquiSW =~ /New Stuff/i) {`grep -i \"1\$\" $DataIn > $DataTmp`; $DataIn=$DataTmp; if($DataTmp eq $DataTmpa){$DataTmp=$DataTmpb;} # if else{$DataTmp=$DataTmpa;} # else } # if aquiSw if($lA && $Artist ne ".*") {`grep -i \"\^$Artist\" $DataIn > $DataTmp`; $DataIn=$DataTmp; if($DataTmp eq $DataTmpa){$DataTmp=$DataTmpb;} # if else{$DataTmp=$DataTmpa;} # else } # if $IA if($lL && $Label ne "*"){`grep -i \"\|$Label\" $DataIn > $DataTmp`; $DataIn=$DataTmp; if($DataTmp eq $DataTmpa){$DataTmp=$DataTmpb;} # if else{$DataTmp=$DataTmpa;} # else } # if $IL if($lN && $LabelNo ne "*"){`grep -i \"\|$LabelNo\" $DataIn > $DataTmp` +; $DataIn=$DataTmp; if($DataTmp eq $DataTmpa){$DataTmp=$DataTmpb;} # if else{$DataTmp=$DataTmpa;} # else } # if $IN
      Interestingly enough, the file is never opened.

      The reason is that the external program 'grep' is opening the file itself.

      Any reason that the grep line is enclosed in ``?

      Backticks (``) run an external program, like the grep here.

      My suggestion was to not use backticks at all, as Perl is perfectly capable of doing grep-like jobs all by itself...  and probably a lot faster, too, than when calling the external grep multiple times.  Of course, you'd have to restructure the program accordingly...

      AFAICT, the consecutive runs of grep (in combination with the use of the temp files) achieve to extract lines where all the tested conditions match.  A restructured solution without using grep could look something like this:

      ... LINE: while (<$fh>) { if ($aquiSW =~ /New Stuff/i) { next LINE unless /1$/; } if ($lA && $Artist ne ".*") { next LINE unless /^\Q$Artist/i; } if ($lL && $Label ne "*") { next LINE unless /\|\Q$Label/i; } # ... if ($lT && $Title ne "*") { # split $Title into @words... for my $word (@words) { next LINE unless /\Q$word/i; } } # ... # we only get here if all the tested conditions matched print; }