Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use `\sort ...`?

Tags:

reference

perl

I am wondering what \sort ... returns.

After executing the following line

my $y = \sort qw(one two three four five);

$y is a reference to a scalar. I actually expected a reference to an array: the array with the sorted elements (five, four, one, three, two). When dereferencing $y (for example print $$y), I get two, the last element of the sorted list.

Is there any useful thing I can to with \sort(...)?

like image 850
René Nyffenegger Avatar asked Mar 24 '17 10:03

René Nyffenegger


2 Answers

According to perldata assigning a scalar to a list of values, assigns the last value of the list to the scalar. So

$foo = ('cc', '-E', $bar);

assigns the value of variable $bar to the scalar variable $foo.

According to perlref, taking a reference to an enumerated list is the same as creating a list of references. Hence,

my $y = \sort qw(one two three four five);

is equivalent to

my $y = \(sort qw(one two three four five));

which is equivalent to

 my $y = \(sort qw(one two three four five))[-1];

which will give a reference to the last value of the sorted list, i.e. the scalar value "two".

like image 159
Håkon Hægland Avatar answered Sep 30 '22 07:09

Håkon Hægland


sort returns a list.

\LIST (like \($x,$y,42)) produces another list containing references to each element of the original list (\$x,\$y,\42).

So \sort ... returns references to the elements of a sorted list.

Now in scalar context, $foo = LIST assigns the last element of the list. Putting this altogether,

my $y = \sort qw(one two three four five);

assigns a reference to the last sorted element to $y, or

print $$y;        # "two"

I can't think of any good use cases for this feature, but that is not very good evidence that one doesn't exist.

like image 36
mob Avatar answered Sep 30 '22 06:09

mob