Hello. I'm trying to convert an awk script I wrote to perl (which I just started self-teaching). I tried the a2p command but I couldn't make sense of most of it.
Here was the awk code:
BEGIN{
FS = ","
print "NAME\tLOW\tHIGH\tAVERAGE"
a=0
}
{
if(a==0){
a+=1
}
else{
if(high[$3]<$4)
high[$3] = $4
else if (low[$3]>$4 || low[$3]==0)
low[$3] = $4
average[$3] += $4
count[$3] += 1
}
}
END{
for(b in high){
average = average/count
printf "%s\t%d\t%d\t%.2f\n",b, low, high, average
}
}
So far this is what I got:
#!/usr/bin/perl
print "NAME\tLOW\tHIGH\tAVERAGE\n";
$a=0;
if($a==0){
$a+=1
}
elsif{
}
I'm not sure how to convert this part to perl:
else{
if(high[$3]<$4)
high[$3] = $4
else if (low[$3]>$4 || low[$3]==0)
low[$3] = $4
average[$3] += $4
count[$3] += 1
}
}
The awk code was to use a .csv file as input thus the $3 and $4
Your turn next:
I got your awk code to run against a dummy input file. I cannot see why your sample ran for you - however after fixing syntax I got an awk
source file t.awk
. t.lis is the file created by a2p. You need to work on reconciling the a2p output.
I ran this command with some errors as below:
./a2p.exe t.awk > t.lis
Unrecognized character ' in file t.awk line 2--ignoring. just remove the "awk" and tic marks I had them in there for convenience
Unrecognized character ' in file t.awk line 36--ignoring.
Please check my work on the 2 lines I've marked with "#???". This needs looking at.
The operation I've selected may be wrong for the operand types.
t.awk is:
awk '
BEGIN{
FS = ","; print "NAME\tLOW\tHIGH\tAVERAGE"; a=0;
}
# main
{
if(a==0)
{
{ a+=1}
}
else
{
if(high[$3]<$4)
{
high[$3] = $4
}
else
if (low[$3]>$4 || low[$3]==0)
{
low[$3] = $4
average[$3] += $4
count[$3] += 1
}
}
}
#end main
END {
for(b in high)
{
average = average/count
printf ("%s\t%d\t%d\t%.2f\n",b, low, high, average)
}
}
'
t.lis is the perl output with minor issues I cannot fix.
#!/usr/bin/perl
eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
if $running_under_some_shell;
# this emulates #! processing on NIH machines.
# (remove #! line above if indigestible)
eval '$'.$1.'$2;' while $ARGV[0] =~ /^([A-Za-z_0-9]+=)(.*)/ && shift;
# process any FOO=bar switches
$, = ' '; # set output field separator
$\ = "\n"; # set output record separator
$FS = ',';
print "NAME\tLOW\tHIGH\tAVERAGE";
$a = 0;
# main
while (<>) {
chomp; # strip record separator
@Fld = split(/[,\n]/, $_, -1);
print $_ if $awk;
if ($a == 0) {
{
$a += 1;
}
}
else {
if ($high{$Fld[(3)-1]} lt $Fld[(4)-1]) { #???
$high{$Fld[(3)-1]} = $Fld[(4)-1];
}
elsif ($low{$Fld[(3)-1]} gt $Fld[(4)-1] || $low{$Fld[(3)-1]} == 0) { #???
$low{$Fld[(3)-1]} = $Fld[(4)-1];
$average{$Fld[(3)-1]} += $Fld[(4)-1];
$count{$Fld[(3)-1]} += 1;
}
}
#end main
}
foreach $b (keys %high) {
$average{$b} = $average{$b} / $count{$b};
printf "%s\t%d\t%d\t%.2f\n", $b, $low{$b}, $high{$b}, $average{$b};
}
2 Likes