Several Ideas on Perl List Context

來源:互聯網
上載者:User

標籤:

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!

Several Ideas on Perl List Context

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.