my %dispatch: sub create_function { my $id = shift; open my $fh, ">", "file_nr_$id" or die "... $!"; return sub { my $line = shift; print $fh $line; } } $dispatch{$_} = create_functions($_) for @list_of_chromosomes; # ... # later when reading the file, assuming you have obtained a $line and an id $id from the input: $dispatch{id}->($line);