FILE2 AAA text1 text2 text3 EOAAA BBB text4 EOBBB CCC text5 text6 text7 text8 EOCCC #### FILE1 SEGMENT1 text1 text2 text3 EOS1 SEGMENT2 text4 EOS2 SEGMENT3 text5 text6 text7 text8 #### FILE3 P201 text1 text2 text3 EOP201 P333 text4 EOP333 P588 text5 text6 text7 text8 EOP588 #### use strict; my @jobs = ( 'file2.txt|AAA|EOAAA', 'file1.txt|SEGMENT3|EOS3', 'file3.txt|P333|EOP333' ); for (@jobs) { my ($file, $beg, $end) = split /\|/; my $first_line = 1; my @lines = (); print "Opening file: '$file'\n", " beg: '$beg' end: '$end'\n"; open (INFILE, "<$file") or die "Could not open '$file': $!\n"; while () { if (/$beg/ .. /$end/) { chomp; print " first: '$_'\n\n" if $first_line; $first_line = 0; push (@lines, $_); } } print "$_\n" for @lines; print "-" x 30, "\n\n"; undef @lines; } #### Opening file: 'file2.txt' beg: 'AAA' end: 'EOAAA' first: 'AAA' AAA text1 text2 text3 EOAAA ------------------------------ Opening file: 'file1.txt' beg: 'SEGMENT3' end: 'EOS3' first: 'SEGMENT3' SEGMENT3 text5 text6 text7 text8 ------------------------------ Opening file: 'file3.txt' beg: 'P333' end: 'EOP333' first: 'FILE3' FILE3 P201 text1 text2 text3 EOP201 P333 text4 EOP333 ------------------------------ #### if ((/$beg/ .. /$end/) or (/$beg/ .. eof())) {