Find Nan Or Zero In One Column And Output Content Of The Second Column
Hi,
I want the contents of column 2 (when NAN/0)in file1.txt to be replaced by the content of column1:
file1.txt:
file for parsing
mnot NAN
PU1 0
PU2 ets
munt tsu
PU3 ttsm
munt2 0
Required output:
file for parsing
mnot mnot
PU1 PU1
PU2 ets
munt tsu
PU3 ttsm
munt2 munt2
my code is not giving the right output:
#!usr/bin/perl
use warnings;
use strict;
use diagnostics;
open(IN, "<", "file1.txt") or die "Can't open file for reading:$!";
open(OUT, ">", "outfile.txt") or die "Can't open file for writing:$!";
my $header = <IN>;
print OUT $header;
while (<IN>){
chomp;
my @sections = split(/\t/);
$sections[1] = 0; # Error: initialization in wrong place
$sections[2] = 0; # Error: s.o., also array index in perl starts at 0!
if (($sections[2] eq 'NAN') || ($sections[2] == 0)) { # Error: always true because you set $sections[2] = 0!
# Error: the first and second column would be in $section[0], $section[1]
#print OUT $sections[1], "\t", $sections[1], "\n";
print OUT "$sections[1]\n"; # Error: you commented away the correctly formatted output (minus wrong array index)
}
else {
#print OUT $sections[1], "\t", $sections[2], "\n";
# Error: s.o.
print OUT "$sections[2]\n"; # Error: you commented out the correctly formatted output (minus wrong array index)
}
}
Please help!
• 2,194 views
•
link
0 answers
No answers yet.
Log in to answer this question.
Can you paste the incorrect output? And why are you setting sections[1] and sections[2] to 0?
That is really a very simple mistake, hint: you are overwriting whatever you read. In fact I think that this is a simple programming question which should not be answered here, there are simply too many simple mistakes, you need to learn basics about perl programming first. I'll mark the mistakes in your code anyway.
In addition to Michael's comment, your example input lacks a header line, so you'll still get
mnot NANin the output if you actually used the functional script with the example input.cat file.txt | awk '{if ($2 == "NAN" || $2 == 0) print $1\t$1;else print $0}'