my $count = 0; my $fh_out; while (<$fh_in>) { if (!defined($fh_out)) { my $fname = sprintf('%s-%d.%s', $base, $count++, $ext); open($fh_out, '>', $fname) or die("Unable to create \"$fname\": $!\n"); } print $fh_out $_; if ($. % $num_lines == 0) { undef($fh_out); } }