FreeKB - Nested while loop in Perl
Nested while loop in Perl

Home > Search


Let's say file1.txt contains these lines:

FILE ONE LINE ONE
FILE ONE LINE TWO
FILE ONE LINE THREE

 

Let's say file2.txt contains these lines:

file 2 line 1
file 2 line 2
file 2 line 3

 

The following script will loop through each line in file1.txt and then do a nested loop through each line in file2.txt.

#!/usr/bin/perl

use strict;
use warnings;

my $file1 = "/path/to/file1.txt";
my $file2 = "/path/to/file2.txt";


open(OUTER, "<", $file1) or die "cannot open $file1 $! \n";
while (my $outer_line = <OUTER>) {
  print $outer_line;

  open(INNER, "<", $file2) or die "cannot open $file2 $! \n";
  while (my $inner_line = <INNER>) {
    print $inner_line;
  }
  close INNER;

}
close OUTER;

 

Running this script will produce the following output.

FILE ONE LINE ONE
file 2 line 1
file 2 line 2
file 2 line 3
FILE ONE LINE TWO
file 2 line 1
file 2 line 2
file 2 line 3
FILE ONE LINE THREE
file 2 line 1
file 2 line 2
file 2 line 3

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments