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

I am wondering what \sort ... returns.

After completing the next line

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

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

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

+5
source share
2 answers

sort returns a list.

\LIST (for example, \($x,$y,42) ) creates another list containing links to each element of the original list (\$x,\$y,\42) .

So, \sort ... returns links to items in a sorted list.

Now in a scalar context, $foo = LIST assigns the last element of the list. Introducing this at all,

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

assigns a link to the last sorted item on $y or

 print $$y; # "two" 

I cannot come up with any good use cases for this function, but this is not very good evidence that this does not exist.

+4
source

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

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

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

According to perlref , a link to an enumerated list is the same as creating a list of links. Hence,

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

equivalently

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

which is equivalent

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

which will give a link to the last value of the sorted list, that is, the scalar value is two.

+5
source

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


All Articles