cosimo has asked for the wisdom of the Perl Monks concerning the following question:
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));
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: XS: Converting a data structure in a string
by creamygoodness (Curate) on Nov 04, 2005 at 16:57 UTC | |
by cosimo (Hermit) on Nov 06, 2005 at 17:24 UTC | |
|
Re: XS: Converting a data structure in a string
by tirwhan (Abbot) on Nov 04, 2005 at 16:27 UTC | |
by creamygoodness (Curate) on Nov 04, 2005 at 17:07 UTC | |
by tirwhan (Abbot) on Nov 04, 2005 at 17:12 UTC | |
by creamygoodness (Curate) on Nov 04, 2005 at 17:28 UTC | |
by cosimo (Hermit) on Nov 06, 2005 at 17:13 UTC |