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.
The reason it's hanging is because you forgot to use
chomp
after reading fromFILE
. So there's a newline at the end of$_
, and it's executing two shell commands: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 noSatheesh
command.Also, since you're redirecting the output of
grep
toout.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 thetee
command.Here's the fix: