http://qs321.pair.com?node_id=728395


in reply to Re: how to comment the lines if found a match
in thread how to comment the lines if found a match

This is how my program looks like now. I tried this but the grep here is not returning right value, its returning 1 as if its matching all the time.

#!/usr/bin/perl -w
open(MATCH_PATTERN,"< temp1");
open(FILE_TO_LOOK,"< temp2");
open OF, "> temp3";

while ($m =<MATCH_PATTERN>)
{
print "reading the current text to match \n $m \n";
seek (FILE_TO_LOOK ,0, 0);
while ($l= <FILE_TO_LOOK>) {
print "reading the textline to look for match \n $l \n";
@found = grep ($m, $l) ;
$match = @found;
if ($match == 1)
{
print "now the match is \n $match \n";
print OF "#$l";
}

}
}
close FILE_TO_LOOK;
close MATCH_PATTERN;
close OF;
  • Comment on Re^2: how to comment the lines if found a match

Replies are listed 'Best First'.
Re^3: how to comment the lines if found a match
by gwadej (Chaplain) on Dec 05, 2008 at 21:59 UTC

    You are misunderstanding the use of grep.

    In your example, grep will always return $l unless $m happens to be 0 or an empty string.

    Instead of grep, you probably want a regular expression.

    if($l =~ /\Q$m\E/) { print "We matched\n"; print OF "$$l"; }

    You probably also want to use chomp in the outer loop to remove the line ending from $m.

    You are also writing the file multiple times with different lines commented each time. You might want to generate a list of the expressions to match at the beginning and then loop over the file once.

    G. Wade