in reply to How to restart a while loop that is iterating through each line of a file?

This may not be the most efficient way to do it (seek would probably be more efficient, and using an array to store the 16 lines certainly more efficient), but if you opened your $fh input file handle within the for loop, then the file handle would be reset to the beginning of the file each time through the loop and you would get your first 16 lines appended each output file.

As a side note, also note that when you're reading from a file handle, the $. special variable contains the number of the file line being read, so that you don't really need the $count variable, you can just check $. to stop your while loop.

Finally this line:

for (my $i=0; $i<=33; $i++) {
might be written simpler as:
for my $i (0..33) {

Replies are listed 'Best First'.
Re^2: How to restart a while loop that is iterating through each line of a file?
by BillKSmith (Monsignor) on Nov 29, 2016 at 03:32 UTC
    It would be even better to concatenate the sixteen lines into a single string. The range operator (..) can be used with perl style 'for' loops and statement modifiers.
    se strict; use warnings; use autodie; my $file = "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n" ."10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n"; open my $fh, '<', \$file; my $filename = 'Annotation_output'; # Directory removed for testing my $data = ''; $data .= <$fh> for (1..16); for (0..33) { open my $new_fh, '>', "$filename$_.vcf"; print $new_fh $data; close $new_fh; }
    Bill