By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,670 Members | 1,516 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,670 IT Pros & Developers. It's quick & easy.

File write problem

P: 21
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)
Expand|Select|Wrap|Line Numbers
  1. Aaaaaa
  2. aaaaaaaa aaaaaaaa aaaaaaaa
  3.  
  4. bbbb bbbb bbbb bbbb bbbb
  5.  
  6. dddddddddd dddddddddd
  7.  
The Code
Expand|Select|Wrap|Line Numbers
  1. use strict;
  2. use warnings;
  3. use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
  4. print "Content-type: text/html\n\n";
  5. ## NOTE: for Perl 5.6 and earlier
  6.  
  7. my $txf="file.txt";
  8. my $opfile="opf.txt";
  9. # get first line
  10. open(TXF,"$txf"); my $title=<TXF>;  close TXF;
  11.  
  12. # Get rest and write to new file
  13. open(TXF,"$txf");
  14.  readline(TXF); # ignore first line
  15.  while(<TXF>) {
  16.   open(OPF,">$opfile");
  17.    print  $_, "<br>"; # good to screen
  18.  
  19.    #### --- need something here but do not know what ????
  20.  
  21.    print OPF $_; # only writes last line into file
  22.   close OPF;
  23.  }
  24. close TXF;
  25.  
  26. # Finish
  27. print qq~<h2>Done</h2>~;
  28. exit;
  29.  
Hoep someone has the answer. I don't want to use a module for something this small.

Thanks.
Nov 9 '16 #1

✓ answered by Roamer

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

Works fine, thanks again.

Share this Question
Share on Google+
2 Replies


Expert Mod 100+
P: 589
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.
Nov 9 '16 #2

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

Works fine, thanks again.
Nov 9 '16 #3

Post your reply

Sign in to post your reply or Sign up for a free account.