Perl parser acts wierdly with sort and uniq

perl

Solution

Look at the docs for `sort`. If you pass it a sub name it will try to use that for the sorting.

That's why the following are different:

print join '', sort(uniq(split //, lc $hello));
# Prints:  ?acdeinsty

print join '', sort uniq(split //, lc $hello);
# Prints: nice day isn't it?

The second one is equivalent to:

print join '', sort {uniq} (split //, lc $hello);

The `uniq` function will return `0` for all tests, claiming that each character is equal. Therefore `sort` will maintain the same order, reducing the above code to just:

print join '', split //, lc $hello;

One trick to keep `sort` from using the next sub as a comparator is to put a `+` sign in front of the sub name (ty mpapec):

print join '', sort +uniq split //, lc $hello;

Problem

Hi I am a newbie in Perl. I have trouble in understanding the operator precedence. I found a program in Wikipedia page for Ruby ``` "Nice Day Isn't It?".downcase.split("").uniq.sort.join # => " '?acdeinsty" ``` I tried the same thing in Perl but the parser acts wierdly. I have the following program ``` use strict; use warnings; use List::MoreUtils qw(uniq distinct) ; my $hello = q/Nice Day Isn't It?/ ; print join ('', sort ( List::MoreUtils::uniq (split(//, lc $hello )))); # &List::MoreUtils::uniq parses correctly and I need to include & before call. print "\n"; print join('', sort( List::MoreUtils::uniq(split(//, lc $hello, 0)))); ``` Output : ``` '?acdeiiinnstty '?acdeinsty ``` Also I tried for to look how Perl parses the code with B::Deparse module and here is the output ``` perl -MO=Deparse test.pl use List::MoreUtils ('uniq', 'distinct'); use warnings; use strict 'refs'; my $hello = q[Nice Day Isn't It?]; print join('', (sort List::MoreUtils::uniq split(//, lc $hello, 0))); print "\n"; print join('', sort(&List::MoreUtils::uniq(split(//, lc $hello, 0)))); test.pl syntax OK ``` I also get the warning when I simply use uniq as I might clash with future reserved keywords. Any useful links to study about the list precedence and associativity will be very helpful. I referred to perlop Term and list operator section. Thanks in advance.

Original source

Related problems