Re: how to read from more than one files at a time
From: Rob Dixon (rob_at_dixon.port995.com)
Date: 10/16/03
- Next message: Rob Dixon: "Re: Split multidimensional array into 4 multidimensional arrays"
- Previous message: Hacksaw: "Re: finding a blank line"
- In reply to: Perldiscuss - Perl Newsgroups And Mailing Lists: "how to read from more than one files at a time"
- Next in thread: Perldiscuss - Perl Newsgroups And Mailing Lists: "Re: how to read from more than one files at a time"
- Reply: Perldiscuss - Perl Newsgroups And Mailing Lists: "Re: how to read from more than one files at a time"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
To: beginners@perl.org Date: Thu, 16 Oct 2003 08:25:30 +0100
<benjamin.zhou@mbusa.com> wrote:
>
> I need to read from more than one file at a time and do some
> operation on the strings and join them together, and put into
> one output file.
>
> Here is the code. But I noticed the second file never get
> read. It must be sth very simple to overcome this. Can anyone
> give me a hint?
>
> thanks,
> Ben
>
> # Usage: perl jointfiles.pl infile1 infile2 outfile
use strict;
use warnings;
> open (IN1, $ARGV[0]);
> open (IN2, $ARGV[1]);
> open (OUT, ">$ARGV[2]");
As John says,
open IN1, $ARGV[0] or die $!;
open IN2, $ARGV[1] or die $!;
open OUT, ">$ARGV[2]" or die $!;
> print "Input fileis : $ARGV[0], $ARGV[1]\n";
> print "Output file: $ARGV[2]\n";
>
> while(<IN1>)
> {
> chomp;
> $in1=$_;
> <IN2>;
> $in2=$_;
> printf OUT "$in1$in2\n";
> }
You need tp think about what happens when the two files are
different lengths. You may not expect that to happen but your
code should still handle that case. Some symmetry between the
handling of the two files would also be nice. Finally you
should really use 'print' here instead of 'printf'.
This code reads a line from each file and outputs them both
until one or other file is exhausted.
my ($in1, $in2);
while (defined ($in1 = <IN1>) and defined ($in2 = <IN2>)) {
chomp ($in1, $in2);
print OUT "$in1$in2\n";
}
> close(IN1);
> close(IN2);
> close(OUT);
HTH,
Rob
- Next message: Rob Dixon: "Re: Split multidimensional array into 4 multidimensional arrays"
- Previous message: Hacksaw: "Re: finding a blank line"
- In reply to: Perldiscuss - Perl Newsgroups And Mailing Lists: "how to read from more than one files at a time"
- Next in thread: Perldiscuss - Perl Newsgroups And Mailing Lists: "Re: how to read from more than one files at a time"
- Reply: Perldiscuss - Perl Newsgroups And Mailing Lists: "Re: how to read from more than one files at a time"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|