in reply to Printing th entire line with a keyword

If you just want to print the lines containing a particular keyword, then the method you're using is probably the best: It's clear, easy to maintain, and unless you're doing a large amount of processing on very large files, is likely fast enough, to boot.

However, it's possible to do so without reading the file line-by-line. You could do it this way:

$ cat t.pl #!/usr/bin/perl use strict; use warnings; my $t; { # A: Slurp in the entire file local $/; $t = <DATA>; } # B: Scan the entire file for a lines containing either # of the words 'fox' or 'wood', and print them. + print "<$_>\n" for $t=~/^(.*?(?:fox|wood).*?)$/gm; __DATA__ Now is the time for all good men to come to the aid of their party. The quick red fox jumped over the lazy brown dog. How much wood can a woodchuck chuck? If a woodchuck could chuck wood? $ perl t.pl <party. The quick red fox jumped> <wood can a woodchuck chuck? If> <a woodchuck could chuck wood?>

You'll want to read perldoc perlre for the details of the regular expression used. In it, I use two features that I only use rarely.

...roboticus

When your only tool is a hammer, all problems look like your thumb.

Replies are listed 'Best First'.
Re^2: Printing th entire line with a keyword
by Anonymous Monk on Dec 31, 2012 at 05:23 UTC

    Is there a way using grep?

    Because the corresponding code in shell script is like grep "searchkeyword" $filetobesearched> $outputfile

      It's even easier with grep. But in perl, grep wants to match against a list, so you'll be back to reading line-by-line:

      #!/usr/bin/perl use strict; use warnings print "<$_>\n" for grep {chomp; /(fox|wood)/} <DATA>; __DATA__ Now is the time for all good men to come to the aid of their party. The quick red fox jumped over the lazy brown dog. How much wood can a woodchuck chuck? If a woodchuck could chuck wood?

      This should give the same result. (Note: the chomp isn't required, but I wanted to match the output of the previous code, so I put it in.)

      ...roboticus

      When your only tool is a hammer, all problems look like your thumb.

        Thank you :)