$counter = 1; open(DATA, "export.dat")||die "Cannot open export.dat for read:$!\n"; while(){ $temp_line = $_; if($temp_line =~ /^1(\d*)/){ if($counter > 1 ){ #No temp file yet if this is the first record close TEMP||die "Cannot close temp.dat:$!\n"; &output_data(); } open(TEMP, ">$temp.dat")||die "Can't open temp.dat:$!\n"; print TEMP $temp_line; $counter ++; } elsif(/\S+/){ print TEMP $temp_line; } } close DATA||die "Cannot close $in_dir/export.dat (weird):$!\n"; close TEMP||die "Cannot close $in_dir/temp.dat:$!\n"; &output_data(); sub output_data{ #do stuff with temp.dat }