Perl sort array / list using comma or dot to concatenate strings

I have:

#!c:\Dwimperl\perl\bin\perl.exe use strict; use warnings; # define an array my @letters = ('b', 'c', 'a', 'e', 'd'); print sort @letters , "\n"; 

Outputs: abcdePress any key to continue . . . abcdePress any key to continue . . . Why is there no return line?

Then I tried using the period concatenation operator:

 #!c:\Dwimperl\perl\bin\perl.exe use strict; use warnings; # define an array my @letters = ('b', 'c', 'a', 'e', 'd'); print sort @letters . "\n"; 

Output: 5 Press any key to continue . . . 5 Press any key to continue . . .

Why does \n work here, but returns the length of the array?

Any links to official documentation will help.

+6
source share
1 answer

When you do

 print sort @letters . "\n"; 

what you are really doing is evaluating @letters in a scalar context and adding a new row and then sorting this array. Since the array is 5 in length, you get number 5.

Try the following:

 my @letters = ('b', 'c', 'a', 'e', 'd'); print sort(@letters . "\ntest"); 

And you will output:

 5 test 

sort undefined behavior in scalar context. Thus, you cannot :

 my @letters = ('b', 'c', 'a', 'e', 'd'); print sort(@letters) . "\n"; # This produces no output 

What you probably want to do is something like this:

 my @letters = ('b', 'c', 'a', 'e', 'd'); print join(",", sort(@letters)) . "\n"; 

Output:

 a,b,c,d,e 

In the first scenario, you add \n to the list of letters, and then sort it. So it ends at the beginning. Here is an example

 my @letters = ('b', 'c', 'a', 'e', 'd'); print sort @letters , "\n", 1, 2, 3; 

Outputs:

 # it outputs a newline and then the characters: 123abcde 

In general, it is useful to use parentheses to understand what behavior you want to get.

 my @letters = ('b', 'c', 'a', 'e', 'd'); print sort(@letters), "\ntest"; 

Outputs:

 abcde test 
+9
source

Source: https://habr.com/ru/post/976853/


All Articles