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(...)
?
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".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With