1

I have a tab-delimited text file in which I do some filtering based on certain column values using a while loop. I write the output to a new file. Now I want to use this output file as an input for another while loop. This is the code that I have so far. Something must be wrong because the out2.txt file is empty.

my $table1 = $ARGV[0];
open( my $file, $table1 ) || die "$! $table1"; #inputfile
open( my $filter1, '+>', "out.txt" )  || die "Can't write new file: $!"; #first output
open( my $filter2, '+>', "out2.txt" ) || die "Can't write new file: $!"; #second output

while (<$file>) {
    my @line = split /\t/; #split on tabs
    if ( $line[12] =~ /one/ ) { 
        print $filter1 "$_";
    }   
}

while (<$filter1>) {
    my @line = split /\t/; #split on tabs
    if ( $line[11] =~ /two/ ) { 
        print $filter2 "$_";
    }   
}

The output file out.txt contains the correct information. However the out2.txt is empty. Can someone help me with solving this problem?

1 Answer 1

4

In your script, the "cursor" for the filehandle $filter1 is always set at the end of the file, while it looks like you want to read from the beginning of the file. You can reset the cursor with the seek builtin function.

seek $filter1, 0, 0;  # reset $filter1 to start of file
while (<$filter1>) {
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.