In this answer about lists and arrays, it was described that if we assign a list to a scalar, the last element of the list is assigned to the scalar, and if the same scalar is assigned an array, then the number of array elements is assigned to the scalar.

Hence the question: is it possible in Perl to make an array be perceived as a list when assigned to a scalar? Those. something instead of this:

perl -E '@a = (3,9); $b = @a; say $b' 2 

I could write for example:

 perl -E '@a = (3,9); $b = (@a); say $b' 9 # и $b содержал бы последний элемент @a 
  • And perl -E '@a = (3,9); $b=$a[$#a]; say $b' perl -E '@a = (3,9); $b=$a[$#a]; say $b' perl -E '@a = (3,9); $b=$a[$#a]; say $b' what's not to like It is unlikely that you will receive the last element as in the list, only clearly - Mike
  • @Mike well, you can also through pop @a and through $a[-1] , as well as a research question, you never know. - edem
  • one
    Curiously at all. In the list context, the contents of the array is perfectly expanded into a list. @b=(0,@a,8) contains 0,3,9,8 , while the scalar we get a list inside which contains the number of elements, i.e. scalar context was applied consistently to all elements - Mike
  • one
    @PinkTux One problem, in my $c = (0,(@a)); $ c is 2, because list items are calculated in scalar context. Check what the code does before writing. ideone.com/Iz4vP6 without brackets the same - Mike
  • one
    SO has already been asked this question: stackoverflow.com/a/34688790/1186729 - dionys

1 answer 1

You can make a list from an array using a slice. And, accordingly, the assignment will look like this:

 $b = @a[0 .. $#a]; 

or

 $b = splice(@a); 

Original answer: stackoverflow.com/a/34688790/1186729 .