my (%handle, $fh, $count); $handle{02} = \*OUTPUT; while(my $line = ) { if(substr($_, 0, 9) !~ /\D/) { chomp $line; my $year; ($line, $year) = validLine($_); $line .= "\n"; $count = $year ne "02" ? \$y_count : \$o_count; $fh = $handle{$year} || do { open my($newfh), ">>", $path."year$year.txt" or die "Cannot open file: $!\n"; $newfh; }; } else { $fh = \*DISCARD; $count = \$d_count; } ++$$count; print $fh $line; }