1

I have a perl scrip below that does a fantastic job, however, I how want to perform the same task but on a larger file. The script below is designed for use on a file containing 15 columns, of which data is transposed from 4 (12-15). I need to extend this to columns 12-2550. Is there an easier way of doing this other than manually adding additional if statements?

#! /usr/bin/perl5.8.6 -w

$input = "Baillie.txt";
$output = "Baillie_edited.txt";


open OUTPUT_FILE_HANDLE, ">$output";
close OUTPUT_FILE_HANDLE;
open OUTPUT_FILE_HANDLE, ">>$output";

open INPUT_FILE_HANDLE, "<$input";

$counter = 1;
while (<INPUT_FILE_HANDLE>) {
#print $_;
chomp();
if ($counter == 1) {
    print OUTPUT_FILE_HANDLE "sample\t".$_."\n";
    @header = split /\t/, $_;
}
else {
    $orig_line = $_;
    @line = split /\t/, $_;
        if ($line[12] == 1|1 or $line[12] == 0|1 or $line[12] == 1|0) {
            print OUTPUT_FILE_HANDLE $header[12]."\t".$orig_line."\n";
        }
        if ($line[13] == 1|1 or $line[13] == 0|1 or $line[13] == 1|0) {
            print OUTPUT_FILE_HANDLE $header[13]."\t".$orig_line."\n";
        }
        if ($line[14] == 1|1 or $line[14] == 0|1 or $line[14] == 1|0) {
            print OUTPUT_FILE_HANDLE $header[14]."\t".$orig_line."\n";
        }
        if ($line[15] == 1|1 or $line[15] == 0|1 or $line[15] == 1|0) {
            print OUTPUT_FILE_HANDLE $header[15]."\t".$orig_line."\n";
        }
    }
}
#last if ($counter eq 100000);
$counter++;
close OUTPUT_FILE_HANDLE;
close INPUT_FILE_HANDLE;
exit;
2

Try this : Fisrt, always put after the shebang use strict; use warnings;. Then, use this for loop (adapt the logic to your needs) :

foreach my $count (12..2550) {
    if ($line[$count] == 1|0) {
        print OUTPUT_FILE_HANDLE $header[$count]."\t".$orig_line."\n";
    }
}
  • Sorry, I deleted my comment when you cut the code. There's too much going on in this script that is strange... 0|1 is another thing (0|1 is the same as both 1|0 and 1|1, as far as I know). But accepting that the script "works", your solution correctly generalizes the operation to an extended range of columns. – Kusalananda Feb 13 '18 at 16:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.