use strict; open(IN,'old_file.txt') or die; my $i = 1; while () { if (/^(\d+)\s*$/) { open(OUT,'>new_file'.sprintf("%02d",$i++).'.txt') or die; do { $_ = ; print OUT; } for (1..$1); } }