while (){ if ($_ =~ /HISTORY/../TABLE/){ open(OUTPUT, '>'.$outputfile) or die "Can't create $outputfile.\n"; print OUTPUT "$_\n"; close OUTPUT; } }