Link to home
Start Free TrialLog in
Avatar of gr8thomas
gr8thomas

asked on

awk in perl

system("awk '{print $1 $2 $3}' temp.txt");

I expect only the first 3 columns of the file to get printed. But it prints out all the columns, Why is that?
Thanks
Thomas
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Tintin
Tintin

Why would you even consider forking a process to call awk from Perl, when Perl is a superset of awk?

You can use a2p to convert an awk script to Perl (although the results can be  a little ugly), but for something as basic as what you have, just use:

#!/usr/bin/perl
while (<>) {
   chomp;
   @field = split;
   print "$field[0] $field[1] $field[2]\n";
}
perl -ane 'print"@F[0..2]\n"'
My guess is by the time is reaching the shell, you do not have anything defined for $1, $2 or $3.  When it hits awk, the command has then become:

system("awk '{print }' temp.txt");

which would print out all the columns of the file.

How about this instead of the system call:

open(FILE, "<temp.txt");
while($line=<FILE>) {
  (@F) = split(" ", $line);
  printf ("%s\n", join(" ", @F[0..2]));
}
close(FILE);
If you are forking out to do awk in Perl, you're completely missing the point of using Perl.