#!/usr/bin/perl -w use strict; my $n=0;open(OUT,">$n.out"); while(<>) { print OUT or die "Lost file handle\n"; if (/foo/) {close(OUT);$n++;open(OUT,">$n.out") or die "Can't get file handle\n";} } print "Reached EOF\n"; close(OUT);