No Automatic Dereferencing
Perl does not do any automatic dereferencing for you. You must explicitly dereference using the constructs just described. This is similar to C, in which you have to say *p to indicate the object pointed to by p. Consider
$rarray = \@array; push ($rarray, 1, 2, 3); # Error: $rarray is a scalar, not an array push (@$rarray, 1, 2, 3); # OKpush expects an array as the first argument, not a reference to an array (which is a scalar). Similarly, when printing an array, Perl does not automatically deference any references. Consider
print "$rarray, $rhash";This prints
ARRAY(0xc70858), HASH(0xb75ce8)This issue may seem benign but has ugly consequences in two cases. The first is when a reference is used in an arithmetic or conditional expression by mistake; for example, if you said $a += $r when you really meant to say $a += $$r, you’ll get only a hard-to-track bug. The second common mistake is assigning an array to a scalar ($a = @array) instead of the array reference ($a = \@array). Perl does not warn you in either case, and Murphy’s law being what it is, you will discover this problem only when you are giving a demo to a customer.
Copyright: http://oreilly.com/catalog/advperl/excerpt/ch01.html
There is a reason for that. Perl has mainly three contexts: void, scalar and list. In your last example, for instance, assigning an array to a scalar ($value = @array) forces scalar context on the array, which returns the number of elements that it has. This is far from an inconvenience, and not at all a hard to track bug if you are familiar with the language. Even more, it can lead to very expressive constructs like this:
my $number_of_adults = grep { $_->age > 18 } @persons;
Here, ‘grep’ returns a list with persons of age above 18. But since the scalar assignment forces scalar context, $number_of_adults is set to the amount of elements of the filtered list.
There are many more examples of how this “non-feature” is pretty useful and ingrained in the language culture.
Comment by brunov — April 21, 2009 @ 1:37 PM
Thanks for you suggestion, brunov!
Comment by doqkhanh — April 23, 2009 @ 11:35 AM