At 11:40 AM +0530 11/6/09, Parag Kalra wrote:
Hey Folks,
I Frequently use perl to process 2 files line by line.
Most of the times I compare two files line by line and check if one line is
same to corresponding line of other file, or if one line is substring of
other line etc and many more operations.
The technique which I generally use is to first save lines of two files in 2
different arrays.
Then execute a for loop where I compare corresponding index elements of the
2 arrays.
I guess this is not an optimize solution since if both files are huge
creating large sized arrays may consume lot of memory.
So wanted to know if there is any better approach to process 2 files line by
line.
Sure. Read both files one line at a time in a loop (untested):
open( my $fh1, ...
open( my $fh2, ...
for(;;) {
my $line1 = <$fh1>;
my $line2 = <$fh2>;
last unless( defined $line1 && defined $line2 );
# compare lines
}
One potential problem is if the files do not have the same number of
lines. You can check for $line1 or $line2 containing anything after
the loop has terminated.
--
Jim Gibson
j...@gibson.org
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/