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

I am trying to append a file with some text. But some times it starts with new line. Some times the new is not appearing. So, I tried in so many ways. I am tied here.

#!/usr/bin/perl use warnings; use strict; open (FD,">>text.txt"); my $flag = 0; foreach my $num (0 .. 10) { if ($flag == 1) { print FD $/,$num; } if ($flag ==0) { print FD $num; $flag = 1; } }

Expect Output :

Its old text 0 1 2 3 4 5 6 7 8 9 10

Its working some times and not working some times. Why its happening????

Replies are listed 'Best First'.
Re: Problem with appending files
by Corion (Patriarch) on Jan 21, 2016 at 13:13 UTC

    What is the output when it is working? Have you made sure that the problem is related to appending to a file? Does your script output the expected output when it is writing to STDOUT instead of appending to a file?

      in my actual code

      open (FD,">>OTAPA_Errors"); foreach my $num (@errors) { if ($flag == 1) { print FD $/,$num; } if ($flag ==0) { print FD $num; $flag = 1; } }

      If I run this sometimes a new line is added at the starting. So i removed new line by using flag. But some times the new line missing.

        Is the code inside a loop? Do you reset the flag for the next open of the file? If it's a global variable, you need to reset it to 0, as it keeps the old value. It's better to use strict and scope the flag properly.
        ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

        May be the newline is already in the file you are appending to, only sometimes. Adding a newline accidentially is easy when inspecting a file with some editors under some OSes.

        Maybe something sets or resets $/.

        Note that your code never can go into the if( $flag == 0 ) branch with the code as you show it. Maybe you want to add some debugging statements using warn. Your code can only one get into the $flag==0 branch.

        I can only recommend reducing your code so that you produce a small, self-contained program (20 lines or so) that still has the problematic behaviour.