File Append Issue

A

Anand

After looking at a number of sources which have little to say on appending
to a file I came up with the following piece of code to append a sentence to
a file:

#!/usr/bin/perl

#open(FILE, ">>test1.html") || die $!;
#print FILE "This is a test line added to the file, <br>\n";

$line_to_write="I've appended a line to a file !";
$file_name="test1.html";

open(DAT,">>$file_name");

print DAT "$line_to_write\n";

close(DAT);

The commented and uncommented sections do the same thing though, they create
a second file without the .html extender rather than appending to
test1.html. What am I doing wrong here?

A.
 
K

Kasp

Anand said:
The commented and uncommented sections do the same thing though, they create
a second file without the .html extender rather than appending to
test1.html. What am I doing wrong here?

Try specifying the absolute path to the file test1.html

Also remember to "close" the file once you are done working with it.

Add the following two lines to your code at the top:
use strict;
use warnings;

--
 
A

Anand

Kasp said:
Try specifying the absolute path to the file test1.html

Also remember to "close" the file once you are done working with it.

Add the following two lines to your code at the top:
use strict;
use warnings;
Kasp,

I made the changes recommended but the line indicated below errors with the
following:
print() on closed filehandle DAT at F:\Perl_Work\fileappend.pl line 15.

I presume that it sees the file as being closed when attempting to append
and thus writes a new file but why?

my $line_to_write="I've appended a line to a file !";
my $file_name="c:\test1.html";

open DAT,">>$file_name";

print DAT "$line_to_write\n"; #this line errors

close DAT;

A.
 
K

Kasp

Problem was with the way $file_name is defined. A \ in double quotes gets
interpolated.
The "c:\test.htm" is tansformed to "c:<TAB>est.htm" .... so just use /
instead of \ for file names, paths etc.

Here is the code that worked for me:

use strict;
use warnings;

my $line_to_write="I've appended a line to a file !";
my $file_name="c:/test1.html"; # Used / instead of \ .... \t means TAB

open DAT,">>$file_name";

print DAT "$line_to_write\n"; #this line errors

close DAT;
 
T

Tad McClellan

Anand said:
open DAT,">>$file_name";


You should always, yes *always*, check the return value from open():

open DAT,">>$file_name" or die "could not open '$file_name' $!";
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top