note
Anonymous Monk
<blockquote>
My question is this: Is there a way that an anonymous sub stored as a hash value can have access to its associated key?
</blockquote>
Unlike what several others have said, you <em>can</em>. In the code below, the anonymous sub gets the key belonging to the value passed in as its first argument.
<code>
#!/usr/bin/perl
use strict;
use warnings;
package Cute;
sub TIEHASH {bless {}, shift}
sub STORE {my ($self, $key, $sub) = @_;
$$self{$key} = sub {$sub->($key)}}
sub FETCH {${$_[0]}{$_[1]}}
package main;
tie my %hash, 'Cute';
my $greeting = sub {print "Hello, $_[0]\n"};
$hash{world} = $greeting;
$hash{earth} = $greeting;
foreach my $key (qw /world earth/) {
&{$hash{$key}};
}
__END__
Hello, world
Hello, earth
</code>
440275
440275
41