Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array/list in Perl using comma or dot for string concatenation

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 . . . Why isn't there any line return?

I then 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 . . .

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

Any references to official documentation would help.

like image 718
Robert Rocha Avatar asked Oct 17 '14 02:10

Robert Rocha


1 Answers

When you do

print sort @letters . "\n";

you are really evaluating @letters in a scalar context and appending a newline, and then sorting that array. Since the array is of length 5, you get the number 5.

Try it like this:

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

And you'll output:

5
test

The behavior of sort is undefined in scalar context. So you cannot do:

my @letters = ('b', 'c', 'a', 'e', 'd');
print sort(@letters) . "\n";
# This doesn't produce any output

You probably want to do something like this:

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

Output:

a,b,c,d,e

For the first scenario, you are appending \n to the list of letters, and then sorting it. So it ends up at the beginning. Here's 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 clear on what behavior you want to get.

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

Outputs:

abcde
test
like image 78
hmatt1 Avatar answered Oct 25 '22 04:10

hmatt1