use strict; my @jobs = ( 'file2.txt|CCC|EOCCC', 'file1.txt|SEGMENT3|EOS3', 'file3.txt|P333|EOP333' ); for (@jobs) { my ($file, $beg, $end) = split /\|/; my $first_line = 1; my $state = 0; my @lines = (); print "Opening file: '$file'\n", " beg: '$beg' end: '$end'\n"; open (INFILE, "<$file") or die "Could not open '$file': $!\n"; while () { chomp; $state = 1 if (/$beg/); if ($state) { print " first: '$_'\n\n" if $first_line; $first_line = 0; push (@lines, $_); } $state = 0, last if /$end/; } ## no matching /$end/, so add one push (@lines, $end) if $state; print "$_\n" for @lines; print "-" x 30, "\n\n"; }