What are magic hash key transformations

Some weeks ago I posted a brain-dump that only got reaction like that looks interesting, but I have no idea what you’re talking about, so I’m going to try to explain what I was doing.

Since 5.10, perl supports uvar magic on hashes, though I called it magic hash key transformations because that gives at least tries to describe what it does. This was implemented to make fieldhashes possible. It’s an interface that does only one thing: when a hash element is accessed in any way the callback is called. The callback can’t change the semantics of the operation (unless it dies), all it can do is change the value of the key looked up. So it can transform $hash{A} into $hash{B}.

Variable::Magic: A module making magic accessable from perl (instead of XS). This means you can actually use this stuff without hacking XS (though it will obviously be a bit slower).

Class::Private: a module I wrote and used as example in my previous post. It rewrites $hash{key} to $hash{‘Package::key’} in order to prevent collisions in key values between sub- and super-classes.

Why aren’t more modules using this? Probably because it’s fairly limited in what useful things it can do. I’m sure there are more uses of it, but I can’t think of any (that’s not true, for my previous post I was considering writing Acme::Keys::Rot13). It’s an interface with a limited purpose, though it can be useful sometimes.

Tagged as:

3 Comments

Of interest to me would be concocting a way to not only use references as keys, but to read them back as references (as opposed to mere strings).

Taking off from that, it would be useful to have something similar to field hashes, but using with keys based on value identity rather than referential identity. (Ie. references to objects that have the same state will map to the same key, even if they’re not the same reference.)

The first is not possible with the current API. The latter can be done, if you have a reliable way of serializing the key. I suspect Data::Dumper using sorted keys might be enough to do the trick. It could be kind of expensive though.