How to store null value in Perl hash

I want to use the Perl hash in my C code (XS) as a set, so I only need to store the keys in the hash. Is it possible to store something like zero or another constant value to avoid creating an unnecessary value?

Something like that:

int add_value(HV *hash, SV *value) { // just an example of key char key[64]; sprintf(key, "%p", value); if (hv_exists(hash, key, strlen(key)) return 0; // here I need something instead of ? return hv_stores(hash, key, ?) != NULL; } 

One possible solution would be to keep the value itself, but perhaps there is a special constant for undef or null.

+4
source share
2 answers

&PL_sv_undef is a undef scalar. This is read only. You probably need a fresh undef scanner created with newSV(0) [1] .

The scalar returned by newSV(0) starts with a refcount from one of which the hash "takes hold" when the scalar is stored in it using hv_stores , so the SvREFCNT_dec or sv_2mortal scalar returned is not. (Increase the link count if you save it elsewhere.)


  •  # "The" undef (A specific read-only variable that will never get deallocated) $ perl -MDevel::Peek -e'Dump(undef)' SV = NULL(0x0) at 0x3596700 REFCNT = 2147483641 FLAGS = (READONLY,PROTECT) # "An" undef (It not the type of SVt_NULL that make it undef...) $ perl -MDevel::Peek -e'Dump($x)' SV = NULL(0x0) at 0x1bb7880 REFCNT = 1 FLAGS = () # Another undef (... It the lack of "OK" flags that make it undef) $ perl -MDevel::Peek -e'$x="abc"; $x=undef; Dump($x)' SV = PV(0x3d5f360) at 0x3d86590 REFCNT = 1 FLAGS = () PV = 0 
+3
source

&PL_sv_undef is an undefined value, but you, unfortunately, cannot use it naively in hashes and arrays. Quoting perlguts :

Generally, if you want to store the undefined value in AV or HV, you should not use & PL_sv_undef, but rather create a new undefined value using the newSV function, for example:

 av_store( av, 42, newSV(0) ); hv_store( hv, "foo", 3, newSV(0), 0 ); 
+4
source

All Articles