in reply to Re: Detecting type of output from subs
in thread Detecting type of output from subs

I am building a transport system, I'm going to call user funcions, collecting their output, serialize it with JSON and transmit through a socket.

I don't know what will be in those functions, but would like to serialize to as correct JSON as possible.

The posted code shows that perl it self somehow were able to tell the differense, I would like to do the same in my program.
  • Comment on Re^2: Detecting type of output from subs

Replies are listed 'Best First'.
Re^3: Detecting type of output from subs
by chromatic (Archbishop) on Dec 24, 2010 at 19:24 UTC
    The posted code shows that perl it self somehow were able to tell the differense...

    It doesn't. Apart from the value of $mode, these two lines do the same thing.

    return 42 if $mode eq 'a'; return (42) if $mode eq 'b';

    The parentheses are superfluous; they do not change the behavior in this case.

    In the final case:

    my @l = (42); return @l if $mode eq 'c';

    The return value depends on the context in which the caller of this function invoked it. When a function called in scalar context (as you've shown here) returns an array, that return value evaluates to the number of elements in the array.

    Oh, and the parentheses in the assignment to the array are also superfluous. This code is equivalent:

    my @l = 42;

    If you'd like to learn more about context, the first chapter of Modern Perl explains it in detail.

Re^3: Detecting type of output from subs
by ikegami (Patriarch) on Dec 24, 2010 at 19:06 UTC

    I don't know what will be in those functions, but would like to serialize to as correct JSON as possible.

    Functions return lists of scalars. It is as correct as possible to transmit a list of scalar. You could use a JSON array for that.

    $json->encode( [ f() ] )

    The equivalent of

    my $s = f(); my @a = f();

    is

    my $s = $json_decode(...)->[0]; my @a = @{ $json_decode(...) };