A better `hv_iter`-like API that permits const-ness

[email protected] ("Paul \"LeoNerd\" Evans") Wed, 17 Jun 2026 11:50:56 +0100
Newsgroups perl.perl5.porters
Message-ID <[email protected]>
I recently had occasion to think on the annoyance that the `hv_iter*`
API stores its context within the HV it is looking at. This has a
number of annoyances. Lukas Mai already touches on a bunch of the
Perl-visible consequences in this thread a few years ago:

  https://www.nntp.perl.org/group/perl.perl5.porters/2023/11/msg267259.html

but I found another one just now.

If you ignore HVs for a moment, it is easily possibly to take copies of
(possibly deeply) any Perl structure containing only scalars, arrays,
5.38-style objects, and globs, without modifying the source. To the
point that the source values can all be marked `const SV *` at the C
API level. While in practice we don't do it, we could in theory mark
these in places like

  AV *newAVav(const AV *oav);

However, because of the way that HV iteration stores its context inside
the HV, it is not similarly possible to mark an HV-shallow-clone
function like `newHVhv` as taking a `const HV *ohv`. Thus more in
general you can't write a generic "clone this SV" function as taking a
"const SV *` as its source if you want it to be able to cope with HVs.

I don't have a specific suggestion to make at the moment, but I want to
note that ideally whatever Perl-level "external hash iterators" concept
we come up with, it would be nice if it could be implemented internally
in some way that permitted `const HV *` pointers to act as sources for
that iteration.

-- 
Paul "LeoNerd" Evans

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