open(my $in, '<', "filein.dat") or die("Unable to open filein.dat: $!\n"); my @buf; my $file_count = 0; while (<$in>) { push(@buf, $_); if (@buf == 30) { open(my $fh_out, '>', "file${file_count}.dat") or die("Unable to create file${file_count}.dat: $!\n"); print $fh_out ($_) foreach @buf; @buf = (); ++$file_count; } } if (@buf) { open(my $fh_out, '>', "file${file_count}.dat") or die("Unable to create file${file_count}.dat: $!\n"); print $fh_out ($_) foreach @buf; }