perl oneliner not works .pl script

I am trying to take first 3 columns in a file which matches the word "abc", but i am getting the below error,
<error>
Global symbol "@F" requires explicit package name at ./new.pl
</error>

whereas when i give the below,grep abc /home/test/file.txt|perl -lane 'print \"$F[0] $F[1] $F[2]\" in unix prompt i am getting the result. When i use inside the perl script it fails. When i remove "use strict" it returns nothing.Please help me out

#!/usr/bin/perl
use strict;
use warnings;
print `grep abc /home/test/file.txt|perl -lane 'print \"$F[0] $F[1] $F[2]\"' > a.txt`;

Why do you invoke a Perl one-liner from within a Perl program ??

#!/usr/bin/perl
use strict;
use warnings;
my $file = "/home/test/file.txt";
my @x;
open (F, "<", $file) or die "Can't open $file: $!";
while (<F>) {
  chomp;
  if (/abc/) {
    @x = split;
    print "$x[0] $x[1] $x[2]\n";
  }
}
close(F) or die "Can't close $file: $!";

tyler_durden

Hi,

Another solution:

$ perl -lane 'print(@F[0..2]) if grep(/abc/, $_)' file.txt

Regards,
Birei

Birei,
It works when i put this is unix prompt but its not working inside a perl script,

#!/usr/bin/perl
use strict;
use warnings;
print `perl -lane 'print(@F[0..2]) if grep(/abc/, $_)' /home/test/file.txt > a.txt`;;

<error>
Possible unintended interpolation of @F in string at ./new.pl line 17.
Global symbol "@F" requires explicit package name at ./new.pl line 17.
</error>

Reason i am putting in script is, i have to process like this for different columns also inside a main foreach loop. This loop goes line by line in that file.txt.
Please help me to make this one-liner to work inside the perl script. Thanks.

Regards,
Prabhu

Hi,

I think my last script has an error, it should be like this:

 $ perl -lane '$,=" "; print(@F[0..2]) if grep(/abc/, $_)' file.txt

Here you have the script, test it:

$ cat script.pl
#!/usr/bin/perl
use warnings;
use strict;

$,=" ";
while (<>) {
    chomp;
    my @fields = split;
    print(@fields[0..($#fields>2?2:$#fields)], "\n") if grep(/abc/, $_);
}
$ ./script.pl file.txt
$ ## (Output supressed).

Regards,
Birei