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!

转载于:https://www.cnblogs.com/yangzd1996/p/5404801.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值