If you want to keep your files open (might get problematic if there are too many of them), you can store filehandles in a hash as in the following example:
my %handles;
foreach my $num (1..10){
$file = $num % 5;
open($handles{$file},'>>',"$file.txt") unless exists $handles{$file}
+;
print {$handles{$file}} $num,"\n";
}