1

I am new to Perl. I am trying to execute grep command with perl.

I have to read input from a file and based on the input, the grep has to be executed.

My code is as follows:

#!/usr/bin/perl
use warnings;
use strict;

#Reading input files line by line
open FILE, "input.txt" or die $!;
my $lineno = 1;
while (<FILE>) {

        print " $_";
        #This is what expected.
        #our $result=`grep -r Unable Satheesh  > out.txt`;
        our $result=`grep -r $_ Satheesh  > out.txt`;
        print $result

}
print "************************************************************\n";

But, if I run the script, it looks like a infinite loop and script is keep on waiting and nothing is printed in the out.txt file.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Dinesh
  • 16,014
  • 23
  • 80
  • 122
  • All the `grep` output is going into `out.txt`, not into `$result`. – Barmar Dec 27 '13 at 05:28
  • 2
    Why are you using the `grep` command when Perl has a perfectly good built-in `grep` function? – Barmar Dec 27 '13 at 05:29
  • Are you expecting Satheesh to be the pattern and $_ to be the directory to search in? If so, I think you have those backwards. – tabstop Dec 27 '13 at 05:29

1 Answers1

2

The reason it's hanging is because you forgot to use chomp after reading from FILE. So there's a newline at the end of $_, and it's executing two shell commands:

grep -r $_
Satheesh > out.txt

Since there's no filename argument to grep, it's reading from standard input, i.e. the terminal. If you type Ctl-d when it hangs, you'll then get an error message telling you that there's no Satheesh command.

Also, since you're redirecting the output of grep to out.txt, nothing gets put in $result. If you want to capture the output in a variable and also put it into the file, you can use the tee command.

Here's the fix:

while (<FILE>) {

        print " $_";
        chomp;
        #This is what expected.
        #our $result=`grep -r Unable Satheesh  > out.txt`;
        our $result=`grep -r $_ Satheesh | tee out.txt`;
        print $result

}
Barmar
  • 741,623
  • 53
  • 500
  • 612