use Sub::Name foreach (keys %news_sites) { *{$_} = subname "generator_for_$_" => sub {...} } #### foreach my $key (keys %news_sites) { *{$key} = sub { ... # as the $key variable was declared in the outer scope of the subroutine, # if the code reference survives longer than this scope it will retain its # value warn $key; # this will warn the value used when defining this sub. } }