Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Can an anonymous sub in a hash value know its key?

by jdporter (Paladin)
on Mar 17, 2005 at 06:42 UTC ( [id://440281]=note: print w/replies, xml ) Need Help??


in reply to Can an anonymous sub in a hash value know its key?

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}->(); }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://440281]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (5)
As of 2024-04-19 10:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found