henzcoop has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks, The code below is within a loop structure. I'm trying to figure out why it prints all lines of output to my screen, but only the last line of output to the OUT file. Thanks for your input.

{ print "pos $i $testseq\n"; open OUT, ">results5"; print OUT "pos $i $testseq\n"; close OUT; }

Replies are listed 'Best First'.
Re: output file gives only last line
by GrandFather (Saint) on Jun 09, 2015 at 02:03 UTC

    Move the file open and close outside the print loop. Note too that you should always check open results, use lexical file handles and use the three parameter version of open:

    open my $out, '>', $fileName or die "Can't open '$fileName': $!\n"
    Perl is the programming world's equivalent of English
Re: output file gives only last line
by jeffa (Bishop) on Jun 08, 2015 at 23:36 UTC

    That is because you overwrite the file each time you open it. Try appending instead:

    open OUT, ">>results5";

    Also, consider checking the results from open and responding accordingly to errors:

    open OUT, ">>results5" or die "Cannot write to output: $!\n";

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: output file gives only last line
by sandy105 (Scribe) on Jun 09, 2015 at 10:58 UTC

    from what code you have posted

    { print "pos $i $testseq\n"; open OUT, ">results5"; print OUT "pos $i $testseq\n"; close OUT; }

    You have print statements which print to your screen but when you open the file and print to the file using print filehandle i.e. print OUT ..It prints to the file..So only the last print stmt shows up in the file .You can open this file at the beginning of the loop and change all print statements to print filehandle i.e. print OUT

    as an alternative you can redirect the stdout of your script by redirecting it to a file like below (so that it will write all print statements to your log file)

    perl script1.perl >> script1.log #redirect stderror Also as below perl script1.perl >> script1.log 2>&1
Re: output file gives only last line
by henzcoop (Novice) on Jun 09, 2015 at 19:23 UTC

    Thanks! You guys are the best! Really appreciated the extra tips, too.