Sunday, December 23, 2007

How To Make Mini Bicycle

Perl and the trap of Sriram Srinivasan

Speaking of Perl we should now pay attention to what this language does for us, but especially how it does. Who uses Perl knows that he is able to evaluate an expression depending on the context, for example

@ array = (3,4,5);
$ n = @ array;
print $ n;

This script prints 3, the number of array elements. In fact, the second line uses the array variable in scalar context so it is "natural" to be assigned $ n size. But let's figure out which trap us hides Perl. As some are aware, this language also counts with the reference and is able to do things like:

@ array = (3,4,5);
$ ref = \\ @ array;
print "@ $ ref \\ n";

This code prints the contents of the array as if I had @ array used . The reference is very simple. In this example the reference $ ref is assigned the string "Array", this can be used by prefixing the symbol @ to use it as a list or a symbol such as $ if you want access to an element, for example $ $ ref [0] . To understand better, we invite you to read a nice guide.
Introduced the concept of context and that of reference, we are now ready to understand the trap reported by Sriram Srinivasan. Let's look at the following expression:

$ ref = \\ ($ a, @ b);

At first glance one might think that $ ref will refer to an anonymous array that is the result of ($ a , @ b) . Instead, it is not. Being that the left is a scalar value, this assignment will be evaluated in a scalar context. Emphasis is now on the right side, the brackets take precedence, so their content is evaluated in scalar context, which is equivalent to the last list value (@ b ). Following is evaluated \\ @ b and then the expression equivalent to:

$ ref = \\ @ b;

In conclusion we can say that Perl has a very high level of abstraction, but still must be careful to interpret this as your script.