I'm trying to set up a self-tied hash in an XSUB. The basic idea is that I want to use the tie mechanism to 'on demand' populate the hash, and remove the TIEHASH magic at the same time. That way the first access to the hash goes through the appropriate TIEHASH method, populates the real hash, removes the tie and returns the appropriate value. Subsequent accesses then use the normal (faster) hash access path rather than the tied one. I've mocked this up as normal perl, and it works fine. However, I'm struggling to figure out how to self-tie a hash from an XSUB. I'm using Devel::Peek to compare the data structure built by the perl version with the one built by the XSUB, and I can't get them to correspond. In the XSUB I've tried code like this: /* Create the hash and bless it */ tmphv = newHV(); ref = newRV_noinc((SV*)tmphv); sv_bless(ref, stash); /* Self-tie the hash ('P' magic) */ ref = newRV_noinc((SV*)tmphv); hv_magic(tmphv, (GV*)ref, 'P'); However, this just results in a data structure that sends Devel::Peek into a recursive frenzy, due to the loop from the hash, via the magic table, back to itself. This is obviously wrong. Can some kind soul explain how the perl equivalent allows self-ties but avoids this self-referential loop? Many thanks, Alan BurlisonThread Next