in reply to read from two files with nested while loops

Try the following:
open A, '1.dat' or die $!; while (my $lineA=<A>){ open B, '2.dat' or die $!; while(my $lineB=<B>){ print $lineA,' ', $lineB; } close B; }
Did you notice the difference? You have to reset the second file-handle ("B") so it starts reading from the very beginning for each step of "A".

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Replies are listed 'Best First'.
Re^2: read from two files with nested while loops
by dsheroh (Monsignor) on Feb 09, 2011 at 10:28 UTC
    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.)
      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.

Re^2: read from two files with nested while loops
by Anonymous Monk on Oct 03, 2014 at 15:25 UTC
    Thanks so much for the insight! I was working half a day on the script and couldn`t understand why it was not doing what I wanted!!! thanks so so much!