如何在Perl哈希中存储null

前端之家收集整理的这篇文章主要介绍了如何在Perl哈希中存储null前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在我的C代码(XS)中使用Perl哈希作为一个集合,所以我只需要将密钥保存在哈希中.是否可以存储类似null或其他常量值的东西以避免创建不必要的值?

像这样的东西:

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,?) != NULL;
}

可能的解决方案之一可能是存储值本身,但是对于undef或null可能存在特殊常量.

解决方法

& PL_sv_undef是undef标量.它是只读的.你可能想要一个新的undef标量,就像使用newSV(0)[1]创建的那样.

newSV(0)返回的标量以refcount为1开始,当标量使用hv_stores存储在其中时,哈希“占有”,因此不要SvREFCNT_dec或sv_2mortal返回的标量. (如果将其存储在其他位置,请增加引用计数.)

>

# "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's 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's 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

猜你在找的Perl相关文章