Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

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

by Anonymous Monk
on Mar 17, 2005 at 10:25 UTC ( [id://440325]=note: print w/replies, xml ) Need Help??


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

My question is this: Is there a way that an anonymous sub stored as a hash value can have access to its associated key?
Unlike what several others have said, you can. In the code below, the anonymous sub gets the key belonging to the value passed in as its first argument.
#!/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

Replies are listed 'Best First'.
Re^2: Can an anonymous sub in a hash value know its key?
by Tanktalus (Canon) on Mar 17, 2005 at 15:12 UTC

    I like the package name.

    I think the lesson to be learned from this is that, with tie, the counterintuitive can be made to work! :-)

Re^2: Can an anonymous sub in a hash value know its key?
by webengr (Pilgrim) on Mar 17, 2005 at 21:42 UTC

    Very nice! That does exactly what I was thinking of. I only wish I had a prize to award!

    PCS
    I was recently asked, "Does your program know when it isn't running?"

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2024-03-19 05:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found