in reply to most appropriate return data type

Which is it, an array or a list?
use warnings; use strict; sub mysub1 { my @fred = qw(The quick brown fox); return @fred; } sub mysub2 { return qw(The quick brown fox); } my $x = mysub1(); print "x: $x\n"; my $y = mysub2(); print "y: $y\n";
Gives:
x: 4 y: fox
You could always use wantarray to return a list or a scalar, depending on the context.

Replies are listed 'Best First'.
Re^2: most appropriate return data type
by Anonymous Monk on Feb 19, 2010 at 15:52 UTC
    Why does $y hold 'fox'? I know that mysub2() returns a list, but I don't know why $y gets assigned to 'fox'.

      The caller forces context on the return. The return value is the result of the evaluation (in the context of the caller) of the last expression in a subroutine (or the expression given to return).

      So..

      • an array in scalar context is the number of items in it.
      • in scalar context the expression ('a','b','c') isn't a list, it's a chain of comma operations:
        In scalar context, the comma operator throws away it's left operand and evaluates the right operand. So the result is c
      • the qw// operator is the comma operator in disguise

      See perlop. Ah, and 'fox' gets assigned to '$y' </nitpick> ;-)

        • the qw// operator is the comma operator in disguise
        It is now. It used to be the split function, in which case, you'd get a split-in-a-scalar-context which would clobber @_ and trigger a warning and return 4. :)

        -- Randal L. Schwartz, Perl hacker

        The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.

      I can't improve on shmem's reply, but that is exactly the reason why you should be clear as to which type you intend to return - and also why you might wish to use wantarray to check for scalar context.