in reply to Re: Return array or list from an XSUB?
in thread Return array or list from an XSUB?

Thanks Joost. Sorry, I should have said that I was returning an array ref from the XSUB, but then post-processing that in Perl. Like so:
$results = $self->_Run( @_ ); # This is the XSUB return @$results if( wantarray ); return undef if( scalar( @$results ) == 0 ); return $$results[ 0 ] if( scalar( @$results ) == 1 ); return $results;
That's the current implementation, but it needs to change as people don't seem to like the fact that it's context aware. They'd rather its return type was constant.
Option 1 is to recode it like this:
$results = $self->_Run( @_ ); # This is the XSUB return @$results;
and simply have the perl wrapper always return an array. The other option is to use XPUSH to return a list instead.

I'm trying to figure out what my users will gain from that implementation over the one above. Can you see anything?

Replies are listed 'Best First'.
Re^3: Return array or list from an XSUB?
by Joost (Canon) on Nov 14, 2007 at 12:45 UTC
    Just a couple of thoughts.
    • It doesn't really matter if you implement this in XS or in a perl "wrapper" - use whatever works, both can do the same thing.

    • All perl statements that can return more than one value are context aware, since all statements can be called in scalar context and there is no fixed way of dealing with that. For instance:

      return (3, 2, 1)

      evaluates to 1 (the last element) in scalar context.

      @array = (3, 2, 1); return @array

      evaluates to 3 (the number of elements) in scalar context.

    It's just a matter of choosing whatever makes the most sense.

    If you're returning something that is "really" a long list of items, then returning the number of elements in scalar context (like an array) is a good choice.

    If you're returning something that is more like a "main" value plus "additional information" then it may make more sense to return the main value in scalar context.

    If you really want to return the same thing in both context, you should just return an array ref.

      Great - thanks!