Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Working with 3 files.... 1

Status
Not open for further replies.

jimj99336

Technical User
Joined
Jan 20, 2007
Messages
2
Location
US
I'm pretty new to Perl programming and need some help.

I have 3 text files that I'm working with, call the File1, File2 and File3.

File1 contains "This is File One"
File3 contains "This is File Three"

File2 needs to be File1 appended with File3. I need to keep File1 as it is.

In BASIC, I'd write a small program something like this:

Open File1 for input as #1 'Open and Read from 1st file.
Open File2 for output as #2 'Open and Write to 2nd file.
While not eof(1) 'Make Sure to get it all.
Input #1, str$ 'Read from file 1
Print #2, str$ 'Write to file 2
Wend 'Go get more (If more)
Close #1 'Close File1
Open File3 for input as #3 'Open and Read 3rd File.
While not eof(3) 'Make sure to get it all.
Input #3, str$ 'Read from file 3.
Print #2, str$ 'Write to file 2
Wend 'Check for more
Close #2 'Close File2
Close #3 'Close file3

I need File1 to stay like it is, but File2 needs to have all the data from File1 and File3.

How is this done in Perl? Can you open a file to read from and one to write to at the same time?

Thanks for any help!

Jim
 
#!/usr/bin/perl
open(INFILE, "./File1") or die;
open(OUTFILE, ">./File2") or die;
while (<INFILE>) {
my $line = $_;
print OUTFILE "$line\n";
}
close INFILE;
open(INFILE, "./File3") or die;
while (<INFILE>) {
my $line = $_;
print OUTFILE "$line\n";
}
close INFILE;
close OUTFILE;

Use ">>./File2" if you have closed the file and need to open for append.

Mark
 
Mark,

Perfect! Worked Great.

Thanks,

Jim
 
just another way to do it:

Code:
#!/usr/bin/perl

open(OUT, ">>File2.txt") or die;
{
   local @ARGV = ('File1.txt','File2.txt');
   while(<>){
      print OUT;
   }
}
close(OUT);
print "finished";

You can open File1 in append mode to begin with, if the file does not exist perl will still create a new file or append to the existing file. Or open in write mode '>' to make sure any existing file is overwritten first.

- Kevin, perl coder unexceptional!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top