#!/usr/bin/perl -w use strict; use warnings; my $counter=0; open(DATA, "export.dat")||die "Cannot open export.dat for read:$!\n"; while(){ if (/^1(\d*)/) { if ($counter > 0) { #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"; $counter = 0; } if (/\S+/) { print TEMP $temp_line; ++$counter; } } close DATA||die "Cannot close $in_dir/export.dat (weird):$!\n"; if ($counter > 0) { close TEMP||die "Cannot close $in_dir/temp.dat:$!\n"; } &output_data(); sub output_data{ #do stuff with temp.dat }