After giving what I believed to be a complete answer yesterday, I realized that it still wasn't quite correct.
It is true that subroutines return lists not arrays, but
when called in scalar context they dont necessarily return the scalar value of that list.
The most obvious example of this is localtime() whose return values in scalar and list context have little to do with one another. Another example happens to be fetchrow_array()
From the DBI pod:
In a scalar context, fetchrow_array returns the value of the first field. An undef is returned if there are no more rows or if an error occurred. Since that undef can't be distinguished from an undef returned because the first field value was NULL, you should exercise some caution if you use fetchrow_array in a scalar context.
Using my logic, in scalar context we'd get the last field not the first.
The moral of the story is that the behavior of a subroutine in scalar context can't be determined from its list context return value.
Here are three subs that return the same values in list context, but behave differently in scalar context:
#!/usr/bin/perl -wT
use strict;
sub test1 {
return @{[ qw(A B C) ]};
}
sub test2 {
return qw(A B C);
}
sub test3 {
return wantarray ? qw(A B C) : 'I like jellybeans';
}
print "List context\n",
" test1: ", join(', ',test1()), "\n",
" test2: ", join(', ',test2()), "\n",
" test3: ", join(', ',test3()), "\n",
"\nScalar context\n",
" test1: ", scalar test1(), "\n",
" test2: ", scalar test2(), "\n",
" test3: ", scalar test3(), "\n";
=OUTPUT
List context
test1: A, B, C
test2: A, B, C
test3: A, B, C
Scalar context
test1: 3
test2: C
test3: I like jellybeans
-Blake
|