The question isn't much different from asking if a string which is a hash value can know which key
of the hash it belongs to. The problem is that values can move around. What if a given value (string or sub) is the value for more than one key? The other factor that impacts how this could be done is: How are you creating the anonymous subs? If you have access to that code, then a solution might be as simple as making
a lexical variable to hold the key value, which the anon sub then closes over.
But again, this presumes you can programmatically prevent a value from being copied or moved to another (incorrect) key later.
sub make_sub_for_given_key
{
my( $key ) = @_; # amongst other arguments
return sub {
# this sub "knows" what $key is, forever.
print "Hi! I belong to key '$key'\n";
}
}
my $key = "Tuesday";
my %hash;
$hash{ $key } = make_sub_for_given_key( $key );
# later on, ask each sub what key it belongs to:
for $key ( keys %hash ) {
$hash{$key}->();
}