Karl
Karl

Reputation: 21

Awk's output in Perl doesn't seem to be working properly

I'm writing a simple Perl script which is meant to output the second column of an external text file (columns one and two are separated by a comma).

I'm using AWK because I'm familiar with it.

This is my script:

use v5.10;
use File::Copy;
use POSIX;

$s = `awk -F ',' '\$1==500 {print \$2}' STD`;
say $s;

The contents of the local file "STD" is:

CIR,BS  
60,90
70,100
80,120
90,130
100,175
150,120
200,260
300,500
400,600
500,850
600,900

My output is very strange and it prints out the desired "850" but it also prints a trailer of the line and a new line too!

ka@man01:$ ./test.pl 
850

ka@man01:$

The problem isn't just printing. I need to use the variable generated by awk "i.e. the $s variable) but the variable is also being reserved with a long string and a new line!

Could you guys help?

Thank you.

Upvotes: 1

Views: 170

Answers (3)

glenn jackman
glenn jackman

Reputation: 246877

The reason you get 2 newlines:

  1. the backtick operator does not remove the trailing newline from the awk output. $s contains "850\n"
  2. the say function appends a newline to the string. You have say "850\n" which is the same as print "850\n\n"

Upvotes: 0

brian d foy
brian d foy

Reputation: 132812

perl can do many of the things that awk can do. Here's something similar that replaces your entire Perl program:

$ perl -naF, -le 'chomp; print $F[1] if $F[0]==500' STD
850

The -n creates a while loop around your argument to -e.

The -a splits up each line into @F and -F lets you specify the separator. Since you want to separate the fields on a comma you use -F,.

The -l adds a newline each time you call print.

The -e argument is the program to run (with the added while from -n). The chomp removes the newline from the output. You get a newline in your output because you happen to use the last field in the line. The -l adds a newline when you print; that's important when you want to extract a field in the middle of the line.

Upvotes: 1

Sobrique
Sobrique

Reputation: 53488

I'd suggest that you're going down a dirty road by trying to inline awk into perl in the first place. Why not instead:

open ( my $input, '<', 'STD' ) or die $!;
while ( <$input> ) {
    s/\s+\z//;
    my @fields = split /,/; 
    print $fields[1], "\n" if $fields[0] == 500; 
} 

But the likely problem is that you're not handling linefeeds, and say is adding an extra one. Try using print instead, or chomp on the resultant string.

Upvotes: 2

Related Questions