Why Perl Is Not My Favourite Programming Language

26th August 2002


Remember the following important rule: There is no rule that relates the behavior of an expression in list context to its behavior in scalar context, or vice versa. It might do two totally different things. Each operator and function decides which sort of value it would be most appropriate to return in scalar context. Some operators return the length of the list that would have been returned in list context. Some operators return the first value in the list. Some operators return the last value in the list. Some operators return a count of successful operations.

In general, they do what you want, unless you want consistency.

- Larry Wall, the Perl functions manual page, perlfunc

Oh, and -

Never write $$a[$i] when you mean ${$a[$i]} or @$a[$i] when you mean @{$a[$i]}. Those won't work at all.
- Tom Christiansen, The Perl Data Structures Cookbook section 0, General tips (abbreviated)

Case closed.

Addendum (15 July 2009)

Thanks to Stephen Sykes for pointing out this example, by "malloc", of how Perl's list/scalar context behaviour can go horribly wrong:

my $foo;
$foo = reverse reverse 'hello';
print $foo;

This prints out olleh, even though you would think that calling reverse twice would return the original word. However, if you read the API spec for reverse, you will see that it returns a list when called in list context. So the second reverse is operating in list context, just reversing a one element list and returning it. The left most reverse then reverses this "hello" in scalar context, since it is being assigned to a scalar, $foo.

Feedback to <mike@miketaylor.org.uk> is welcome!