in reply to I need to append to text file

open (IFILE1,"Filename1.txt") or die "Can't open file1";
open (IFILE2,"Filename2.txt") or die "Can't open file2";
open (OUTFILE,">OutputFile.txt") or die "Can't open file for writing";

while (<FILE1>){print OUTFILE $_}
while (<FILE2>){print OUTFILE $_}

close IFILE1;
close IFILE2;
close OUTFILE;
A bit long winded, theres probably a one liner to do it, but it'll do the job, and might help to explain file handling in perl into the bargain!

Should also have said that this combines them into a third file - a nice cautious option!

Replies are listed 'Best First'.
Re^2: I need to append to text file
by holli (Abbot) on Jan 18, 2005 at 18:07 UTC
    your code is certainly correct (even if it doesn´t use strict;), but aatlamaz states that he couldn't handle newline problem. That leads me to the assumption, that at least one of the files has no newline at its last line. Thus it must be added.
    So i changed above code to handle that (while also adding argument handling and support for more than two files):
    use strict; my $outfile = pop @ARGV or die "No outfile!\n"; my @infiles = @ARGV or die "No infile(s)!\n"; open OUTFILE, ">$outfile" or die "Cannot open $outfile!\n"; for ( @infiles ) { open (INFILE, $_) or die "Can't open $_!\n"; while ( <INFILE> ) { chomp; print OUTFILE "$_\n"; } close INFILE; } close OUTFILE;


    The script can be called like this:
    shell: perl script.pl file1 file2 fileN outfile

    holli, regexed monk