You can just open all the output files first. Something like this:
#!/usr/bin/perl
use strict;
use warnings;
my %files;
for my $i ( '01' .. '15' ) {
open my $OUT, '>', "output_$i.txt" or die "can not create 'output_
+$i.txt' $!\n";
my $pattern = sprintf 'S%05dGM', $i;
$files{ $pattern } = { fh => $OUT, count => 0 };
}
open my $FH, '<', 'input.txt' or die "can not open 'input.txt' $!\n";
while ( my $line = <$FH> ) {
my $four = ( split /\t/, $line )[ 3 ];
my $key = substr $four, 0, 8;
if ( exists $files{ $key } ) {
print { $files{ $key }{ fh } } $line;
$files{ $key }{ count }++;
}
}
close $FH;
for my $key ( keys %files ) {
unless ( $files{ $key }{ count } ) {
print { $files{ $key }{ fh } } "NO HITS\n";
}
}