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}.

Nothing more, nothing less.

AFAIK, there are only 4 modules on CPAN that use it

  • Hash::Util::FieldHash: The original user of this API.
  • Hash::FieldHash: A simpler reimplementation of H::U::F.
  • 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.

In my next post, more about the darker side uvar magic.

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.)

Cannot? I wouldn’t be so sure of that… :-)

Sure it will be ugly internally… but it seems possible to me.

Leave a comment

About Leon Timmermans

user-pic