Mint.K
Mint.K

Reputation: 899

awk command in perl scripts getting error

I am running the below code in my perl script.

my $record = `awk -F'[:;]' '$1 == "Amy"' data.txt`;

However, it's giving me the error:

awk: syntax error at source line 1
 context is
     >>>  == <<< 
awk: bailing out at source line 1

What is causing this error?

Upvotes: 0

Views: 82

Answers (2)

Sobrique
Sobrique

Reputation: 53488

Calling awk in backticks from perl is a pretty nasty thing to do. perl replicates pretty much all the same functionality - all you do is introduce additional overhead, inefficiency and quoting problems (like you've got in your example).

Why not instead:

open ( my $input, '<', 'data.txt' ) or die $!;
my ($record) = grep { (split /[:;]/)[0] eq 'Amy' } <$input>; 

This replicates what you're doing, but you could instead do something altogether more elegant like:

my %person;
while ( <$input> ) { 
    chomp;
    my ( $name, @fields ) = split /[;:]/; 
    $person{$name} = \@fields; 
}

And then:

print join " ", @{$person{'Amy'}},"\n";

Upvotes: 1

Zumo de Vidrio
Zumo de Vidrio

Reputation: 2091

Try to escape the $ sign:

my $record = `awk -F'[:;]' '\$1 == "Amy"' data.txt`;

Upvotes: 2

Related Questions