I need to process hash value depends on value type. Here is code with problem:
I32 keys = hv_iterinit(hash);
for (I32 i = 0; i < keys; i++)
{
char *key = NULL;
I32 key_length = 0;
SV *value = hv_iternextsv(hash, &key, &key_length);
// SvROK(value);
if (SvTYPE(SvRV(value)) < SVt_PVAV)
{
// handle scalar
printf("key %s has scalar value\n", key);
}
else if (SvTYPE(SvRV(value)) == SVt_PVAV)
{
// handle array
printf("key %s has array value\n", key);
}
else if (SvTYPE(SvRV(value)) == SVt_PVHV)
{
// handle hash
printf("key %s has hash value\n", key);
}
}
If I don't use commented line, I have problem with scalar values. For example with following hash {a => "b", c => {d => "e"}}
is produce output:
key c has hash value
key d has scalar value
So here are my questions:
- Do we always have reference returned from
hv_iternextsv()
or sometimes it returns scalar? - Why I don't see scalar value output for key
a
.
Update.
My mistake was in working with result of hv_iternextsv()
. I was thinking that is always a reference. Here is how working code looks like:
I32 keys = hv_iterinit(hash);
for (I32 i = 0; i < keys; i++)
{
char *key = NULL;
I32 key_length = 0;
SV *value = hv_iternextsv(hash, &key, &key_length);
if (!SvROK(value))
{
// handle scalar
}
else
{
if (SvTYPE(SvRV(value)) == SVt_PVAV)
{
// handle array
}
else if (SvTYPE(SvRV(value)) == SVt_PVHV)
{
// handle hash
}
}
}