diamantis has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks!

I expected the following code to read line by line file 1.dat and 2.dat and compare each line of file 1.dat with each line of file 2.dat.

open A, '1.dat' or die $!; open B, '2.dat' or die $!; while (my $lineA=<A>){ while(my $lineB=<B>){ print $lineA,' ', $lineB; } }
Apparently there is something in the behavior of filehandles that I don't understand as the condition in the first while loop does not evaluate true a second time.

example files

1.dat ---- 1 2 3 2.dat ---- a b c
thank you for any sugestions

Replies are listed 'Best First'.
Re: read from two files with nested while loops
by CountZero (Bishop) on Feb 09, 2011 at 06:57 UTC
    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

      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.

      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!