Several Ideas on Perl List Context

According to Beginning Perl Book published by Tsinghua Pub., the list context appears when you are trying to assign some value to a list variable.

1 my @copy = @source;

This is a very simple instance of shallow copy, which usually means you just copied the reference of the source array, none new elements are created and no other memories will be occupied.

  When we assign an array with a hash table, the key-value elements will be converted to a plain list, which is called planarization.

  For example, the following perl codes will print the result below:

1 my %hashtable = (
2  Tom=>12,
3  Jerry=>13,
4  Sam=>17                
5 );
6 my @flattened = %hashtable;
7 print @flattened;
Tom12Jerry13Sam17

*Another thing I want to stress here is, if we want to seperate these flattened elements by a blank space charactor, we need to modify the print statement to this: (Attention to the quatation marks)

1 print "@flattened";

Thus, the result in console will become:

Tom 12 Jerry 13 Sam 17

 

The book has noted one important feature - the advantage of list context:

You can force to obtain it with a pair of brackets.

If we want to assign the first element to a scalar variable, we can simply surround it with brackets, like this:

1 my @array = ('element0','element1');
2 my ($scalar) = @array;
3 print $scalar;

  The result is displayed:

element0

 

  But there is more than that! We can add more scalars to the brackets(as long as the array has enough elements), and the scalars will be assigned by the elements one by one. Code it as follow:

1 my @array = ('element0','element1');
2 my ($scalar0,$scalar1);
3 print "$scalar0\t$scalar1";

  The result is:

element0    element1

 

  Have you found the advantage of list context? If you haven't, see the followint statement:

($leftScalar , $rightScalar) = ($rightScalar , $leftScalar);

  Isn't it beautiful? Usually, especially in some other languages, we have to use a third variable to store one of the two elements and that certainly takes more than this in Perl.

  

  OK! It's what we get this afternoon!

posted @ 2016-04-18 15:54  DT_Moriaty  阅读(142)  评论(0编辑  收藏  举报
TOP