Hello esteemed monks,
I'd like to propose you an interesting challenge. I've never been an XS expert. I'm moving my first steps into these twisty little passages.
I'm coding an XS function that takes an array reference as input and returns a scalar.
Example:
my @list = ('a', 'b', 1, [1,2,3], 'c', {z=>1,y=>2}); print myfunc(\@list); # prints 'a,b,1,ARRAY(1-2-3),c,HASH(z1-y2)';
I came up with the following code that I attach here. I'm missing two main parts.
1) If nth element of list is an arrayref $r, replace $r
in the original list with @$r.
2) If nth element of list is an hashref $r, append
result of perl function F($r) to the result scalar string.
Can you help me?
Code follows:
#include "EXTERN.h" #include "perl.h" #include "XSUB.h" MODULE = html::BaseTag PACKAGE = html::BaseTag PREFIX = html_ +BaseTag_ void html_BaseTag_contentToString_xs(list) AV* list PREINIT: SV* val; SV* ref; SV** list_entry; SV* result; I32 alen = 0, i = 0; PPCODE: /* Initialize result scalar string */ result = newSVpv("", 0); /* Check if list is a valid array and is not empty */ if( list && (alen = av_len(list)) > -1 ) { /* Iterate through the list */ /* fprintf(stderr, " length of list is %d\n", alen); */ for(; i <= alen; i++) { list_entry = av_fetch(list, i, 0); if( list_entry ) val = *list_entry; /* Check if array element is a reference */ /* fprintf(stderr, " type of SV = %d\n", SvTYPE(val)); */ if( SvROK(val) ) { /* Get the corresponding reference value */ ref = SvRV(val); /* Type is array ref */ if( SvTYPE(ref) == SVt_PVAV ) { sv_catpv(result, "*AREF, "); /* XXX splice(@list, i, 1, @ref) */ } /* Type is hash ref */ else if( SvTYPE(ref) == SVt_PVHV ) { sv_catpv(result, "*HREF, "); /* XXX result .= html::BaseTag::tagToString(ref); */ } } else if( SvPOK(val) ) { /* fprintf(stderr, " array element %d is %s\n", i, Sv +PV_nolen(val)); */ sv_catpvn(result, SvPVX(val), SvCUR(val)); sv_catpv(result, ", "); } } sv_catpv(result,"\n"); } EXTEND(SP,1); PUSHs(sv_2mortal(result));
In reply to XS: Converting a data structure in a string by cosimo
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |