Re: Efficient HV fetches without recomputing the key hash

[email protected] ("Paul \"LeoNerd\" Evans") Mon, 8 Jun 2026 21:05:46 +0100
Newsgroups perl.perl5.porters
Message-ID <[email protected]>
On Mon, 18 May 2026 17:50:34 +0100
"Paul \"LeoNerd\" Evans" <[email protected]> wrote:

> If we were to use Magic v2 for "user-defined hashes", or arrays, or
> whatever, that then puts us into a new kind of magic that has to
> actually answer questions - e.g. "get me the element at this
> key/index". Suddenly now there needs to be *exactly one* magic v2
> table on a given SV that provides that full set of API requirements
> to be an array, hash, whatever. There are now has concerns about what
> happens if we try to attach multiple such magics, or if a given magic
> table doesn't provide all the answers, etc. They're all questions
> that can potentially just be solved by `croak("Can't attach this
> magic table")` as part of the sv_magicv2_add() call, but it's still
> something that needs to be thought about.

Ah. So it turns out on some more thought, we actually already have that
with (v1) MAGIC. In particular, we have that with the standard scalar
magics and the `get` function, which a number of magics use to
basically implement some sort of virtual scalar variable. Things like
$! as errno/strerr.

On a search of CPAN for various uses of magic, I've now stumbled upon
this module:

  https://metacpan.org/dist/Errno-AnyString/source/lib/Errno/AnyString.xs#L141

It wants to override the "get" behaviour magic on the $! variable, and
ensure it gets run after the built-in "get" magic, so its version has
effect last. The code it uses to do this is... not great. ;) But
it's probably the best that a regular CPAN module can do.

So perhaps even without virtual magic-driven arrays or hashes, we
already have occasion to think of how virtual magic-driven scalars
actually ought to work, so this can be done better.

-- 
Paul "LeoNerd" Evans

[email protected]
http://www.leonerd.org.uk/  |  https://metacpan.org/author/PEVANS