|Think about Loose Coupling|
Re: Re: Suggestion for teaching Perlby nysus (Parson)
|on Apr 14, 2001 at 18:21 UTC||Need Help??|
You are correct that reverse in a scalar context will reverse the bytes in its argument. So, my $x = reverse($aloha); would result in assigning $x to "olleh".
However, the output of this particular piece of code is not "olleh" at all! The output of above code is just plain old "hello".
Why? Well, it's because in this instance, reverse is being used in a list context. To prove to yourself that it is being used in a list context, run this bit of code through Perl:
What happens now? The result is "goodbyehello"! This is precisely how you would expect reverse to work in a list context: it reverses the order of the elements in the list.
Finally, try this piece of code:
The scalar function forces a scalar context an indeed, the output yields "olleh".
So what is putting reverse($aloha) in a list context? It is our friend, the print function. If you kindly refer to your Camel book, or your Perldoc, or your Learning Perl book or whatever handy refernce you have a available, you will see that print places its arguments into a list context.
So, looking back at our original piece of code, the reason why it prints just plain old "hello", is that it is reversing the elements in the list and not the bytes in the string. Since there is only one element in the list, the list reversed is precisely same as the original list!
Monks, please chime in if this explanation is not exactly accurate.