File write problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Roamer
    New Member
    • Dec 2012
    • 23

    File write problem

    Normally I'm okay writing files, but this is something I have never tried before and am not getting the correct result in the new file.

    A file contains some text with a header. I can grab the header okay. What I want to do is write the entire rest of the file to a new one.

    The problem is, it only writes the last line to the new file.

    Text File (real one would contain a lot more)
    Code:
    Aaaaaa
    aaaaaaaa aaaaaaaa aaaaaaaa
    
    bbbb bbbb bbbb bbbb bbbb
    
    dddddddddd dddddddddd
    The Code
    Code:
    use strict;
    use warnings;
    use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
    print "Content-type: text/html\n\n";
    ## NOTE: for Perl 5.6 and earlier
    
    my $txf="file.txt";
    my $opfile="opf.txt";
    # get first line
    open(TXF,"$txf"); my $title=<TXF>;  close TXF;
    
    # Get rest and write to new file
    open(TXF,"$txf");
     readline(TXF); # ignore first line
     while(<TXF>) {
      open(OPF,">$opfile");
       print  $_, "<br>"; # good to screen
    
       #### --- need something here but do not know what ????
    
       print OPF $_; # only writes last line into file
      close OPF;
     }
    close TXF;
    
    # Finish
    print qq~<h2>Done</h2>~;
    exit;
    Hoep someone has the answer. I don't want to use a module for something this small.

    Thanks.
  • RonB
    Recognized Expert Contributor
    • Jun 2009
    • 589

    #2
    There are a lot of problems with your code but the problem you're asking about is caused by opening the output filehandle inside the loop.

    Take that open call out of the loop and put it up next to the other open call and put the close statement after the loop.

    Comment

    • Roamer
      New Member
      • Dec 2012
      • 23

      #3
      Thanks Ron. I use that method for other stuff, but didn't try it here (my Duhh).

      Works fine, thanks again.

      Comment

      Working...