my $max_line_count = $whatever; my $file_count = my $line_count = 0; my $outfh; sub printAndCount { local $_ = shift; my $lines2print = tr/\n/\n/; # simple way to count \n's if ( $file_count == 0 or $line_count + $lines2print > $max_line_count ) { close $outfh if ( $file_count ); open $outfh, sprintf( ">track%03d.txt", ++$file_count ) or die "open failed: $!"; } print $outfh; $line_count += $lines2print; }