Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

How can I do something like:

my %hash = ("key1" => "value 1", "key2" => "value 2", "key3" => [0,1,2,3,4] );
and store an anonymous AV into in HV?
Fill up the AV using av_store() and then store it into an hash entry using hv_store?

TIA,

Christian Cloutier

Replies are listed 'Best First'.
Re: XS Storing AV in HV entry
by SarahM (Monk) on Apr 04, 2003 at 17:40 UTC
    You just need to put a reference to the AV in the HV. (notice the newRV_inc()) The following code is untested (I don't have a compiler on this computer) but should give you the right idea.
    AV * array = newAV(); HV * hash = newHV(); // use AV_store() to put something in the array HV_store(hash, "key3", 4, newRV_inc((SV *) array), 0);
      This is almost right--you want newRV_noinc, not newRV_inc. The AV you've created already has a refcount of 1, so there's no need to increment it again.

      Note that, if only your XS code accesses the array, you can stick the AV directly in. (It works, AVs are supersets of SVs, at least for this purpose) Do not access an array stored like this from perl code, though, as bad things will happen. (core dumps and fatal errors. Not good)

Re: XS Storing AV in HV entry
by tall_man (Parson) on Apr 04, 2003 at 17:32 UTC
    It sounds like your idea should work. There's a module that might help you experiment with av_store and hv_store before descending to XS code: Array::RefElem.