in reply to Re: read from two files with nested while loops
in thread read from two files with nested while loops

Another option, instead of closing and re-opening B every time, would be to open it once at the start and use seek to reset the file's position:
open my $fhA, '<', '1.dat' or die $!; open my $fhB, '<', '2.dat' or die $!; while (my $lineA=<$fhA>){ seek $fhB, 0, 0; while(my $lineB=<$fhB>){ print $lineA,' ', $lineB; } }
Better still, though, would be to slurp B into an array instead of re-reading the file for every line in A:
open $fhA, '<', '1.dat' or die $!; open $fhB, '<', '2.dat' or die $!; @B_lines = <$fhB>; while (my $lineA=<$fhA>){ for my $lineB (@B_lines) { print $lineA,' ', $lineB; } }
(And I also switched both examples to use lexical filehandles and three-arg open instead of doing it The Old-Style Way because they're better/safer/etc.)

Replies are listed 'Best First'.
Re^3: read from two files with nested while loops
by diamantis (Beadle) on Feb 09, 2011 at 15:49 UTC
    Thanks!

    It is clear to me now. Last night I was somehow confused thinking that the problem was in the outer loop, but now it all makes sense. Thank you.