in reply to using references as keys in a hash.

We've seen a few means of using references as hash keys. That's pretty cool, from a theoretical standpoint--but I was wondering what the practical application could be.

What are examples of using references as hash keys to make problems easier?

My example, if I wanted to keep a hash of my usernames for websites, and put the prepared HTTP request in the hash.

use Tie::RefHash; use HTTP::Request; use Data::Dumper; $r1 = HTTP::Request->new(GET => 'http://www.perlmonks.org/'); $r2 = HTTP::Request->new(GET => 'http://use.perl.org/'); # Etc... tie %sites, 'Tie::RefHash', ($r1, 'Solo', $r2, 'Solo'); print Dumper(\%sites);

It seems too trivial, but that's probably just my lack of vision ;)

--Solo

--
I think my eyes are getting better. Instead of a big dark blur, I see a big light blur.

Replies are listed 'Best First'.
Re: Why use references as keys in a hash?
by steves (Curate) on Feb 23, 2003 at 15:21 UTC

    I have a few examples. I always use Tie::RefHash:

    • A class (package) that needs to keep track of all its instances and look-up by instance when methods are called.
    • An "object mapper" method in a package that takes two sets of objects from classes derived from that package and maps objects from the first to objects in the second. The resulting map is hash: first set objects are the keys; second set objects are the values.
    • An XML template parser tool that, at one point, associates names to pieces of the XML that are stored as trees. Those trees are hash references. Later, some of the processing requires that given a tree we find its name. That reverse lookup hash uses the tree references as the keys and the names as the values.