Mailing List Archive

Sub returning array to scalar
I understand that Perl5.001m "fixes" Perl5 in regards to a subroutine returning an array to a scalar. My tests (given below along with a test script) suggest that the fix may not be appropriate. Specifically, the behaviour of scripts working under Perl4 are different than Perl5 which causes me a lot of grief when it comes to upgrading because it requires much more than a simple change to the #! line. The following code snippet illustrates the issue:

{
require 5.0;
my($value1) = &getList();
$value2 = &getList();
print "Value1=$value1, Value2=$value2\n";
}

sub getList {
my(@list) = ("first","second","third");
return(@list);
}

The results I've obtained are as follows:

SGI, Perl4.036: Value1=first, Value2=third
SGI, Perl5.001l: Value1=first, Value2=third
SGI, Perl5.001m: Value1=first, Value2=3
HP, Perl5.001m: Value1=first, Value2=3

(Note: The script given was modifed for Perl4 by replacing the "my" statements with "local" statements.)

I understand that the subroutine will return an array value and the scalar variable will receive the size of the array unless forced into a list context by the parentheses, but the difference is quite subtle, especially in light of my use of the "my" (and "local" for Perl4) statements.
I've replace the sub return line with the following which ensures a behaviour consistent with Perl4:

return(wantarray?@list:$list[$#list]);

I know now that more robust code can be written using the "wantarray" statement in the subroutine and I have included it in all the subroutines that I know return array values, but I must admit my confidence is shaken a bit. I've always used the "my" statement as a way of not only enforcing the scope of my variables but as a way of "predeclaring" my variables. Now it would appear that this may have backfired on me. I brought this issue up in the news group and even suggested that a test for it be included in the standard Perl install tests but got no significant feedback on my suggestion. What do you think? Is a test of this behaviour included in the latest Perl package? Can you explain why the current behaviour is considered appropriate especially since it breaks existing perl4 scripts?

Thanks for your time,
Tod