Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Re: Loop through 2 files in parallel

by Roy Johnson (Monsignor)
on Nov 10, 2010 at 20:16 UTC ( #870679=note: print w/replies, xml ) Need Help??

in reply to Loop through 2 files in parallel

You definitely don't want to nest your file-reading loops. Instead, try something like this (untested):
while (my $w1 = <FILE> and my $w2 = <FILE2>) { if ($w1 lt $w2) { print "\n"; $w1 = <FILE>; } elsif ($w1 gt $wt) { print "\n"; $w2 = <FILE2>; } else { print $w1; } } # Leftover lines in either file? print "\n" while <FILE>; print "\n" while <FILE2>;

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^2: Loop through 2 files in parallel
by rwitmer (Initiate) on Nov 10, 2010 at 21:07 UTC
    By george, I think this will work. You are truly a monktastic monk! Thanks!
      at least one error in previous code ... while condition is wrong.
      use strict; use warnings; my @FILES; open $FILES[0], '<', 'file1' or die; open $FILES[1], '<', 'file2' or die; my @w = map scalar <$_>, @FILES; my $empty = "blank line\n"; my %map = ( -1 => [ 0 ], 1 => [ 1 ], 0 => [ 0, 1 ], ); while (defined $w[0] && defined $w[1]) { my $cmp = $w[0] cmp $w[1]; print $cmp ? $empty : $w[0]; @w[ @{$map{$cmp}} ] = map scalar <$_>, @FILES[ @{$map{$cmp}} ]; } # Leftover lines in either file? print map $empty, map <$_>, @FILES;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://870679]
[Corion]: Whee! Germanys Grand Central Airport (for Berlin, re-scheduled for the thrid or fourth time, to open now in 2018) has just fired their technical lead
[ambrus]: Corion: Is their budget estimate four times the initial estimate yet? Was the construction late by six months already three months after they started?
[marto]: I'll believe it when I see it. That's been due for many years now :P
[marto]: oddly the last time I was there I saw a zeppelin in flight for the first time
[Corion]: ambrus: I don't know how far the budget estimate has been overrun yet
[Corion]: marto: Heh ;) No, you were likely at Tegel or Schönefeld, the new one ("BER") will be somewhat outside of Berlin ;)
[marto]: Corion Schoenfeld, but my friend has been telling me about this new airport for about 7-8 years now :P
[marto]: I doubt it even exists as a building site :P

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (10)
As of 2017-02-23 11:56 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (346 votes). Check out past polls.