@lines = <>; #Slurp the whole thing. $fh = shift @lines; #First line of whole is FH line $ft = pop @lines; #Last line of while if FT line chomp ($fh,$ft); #get rid of newlines @segments = split /^BH/, join "",@lines; #split it up based on a BH at beginning of line; shift @segments; #First segment will be empty. foreach $segment (@segments) { #loop through segments $segment = "BH".$segment; #replace missing BH at beginning that was removed by split @lines = split /\n/,$segment; #split the segment on new lines chomp @lines; #get rid of newlines $batchhead = shift @lines; #first row is the Batch header foreach $trans (@lines) { #Loop through remaining process($trans, $batchhead); #process individual lines } }