my %handles; foreach my $num (1..10){ $file = $num % 5; open($handles{$file},'>>',"$file.txt") unless exists $handles{$file}; print {$handles{$file}} $num,"\n"; }