Ho bisogno di elaborare il valore di hash dipende dal tipo di valore. Ecco il codice con il problema:Come gestire il tipo di valore hash in Perl XS
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);
}
}
Se non utilizzo la riga commentata, ho problemi con i valori scalari. Per esempio con i seguenti hash {a => "b", c => {d => "e"}}
è produrre output:
key c has hash value
key d has scalar value
Così qui sono le mie domande:
- dobbiamo sempre riferimento tornati da
hv_iternextsv()
o, talvolta restituisce scalare? - Perché non vedo l'output del valore scalare per la chiave
a
.
.
Il mio errore è stato nel funzionamento con il risultato di hv_iternextsv()
. Stavo pensando che è sempre un riferimento. Codice Ecco come lavora assomiglia:
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
}
}
}
mi aspetto il vostro pasta mancano alcune parentesi, perché non verrà compilato. Forse vuoi dire: 'if (SvTYPE (SvRV (value)) == SVt_PVAV)'? – LeoNerd
Codice aggiornato, grazie. –
@ikegami Ho aggiornato la mia domanda. Problema che non vedo l'output del valore scalare per la chiave 'a'. –