Perl parser acts wierdly with sort and uniq -


hi newbie in perl. have trouble in understanding operator precedence. found program in wikipedia page ruby

"nice day isn't it?".downcase.split("").uniq.sort.join # => " '?acdeinsty" 

i tried same thing in perl parser acts wierdly. have following program

    use strict;     use warnings;     use list::moreutils qw(uniq distinct) ;      $hello = q/nice day isn't it?/ ;      print join ('', sort ( list::moreutils::uniq (split(//, lc $hello ))));  # &list::moreutils::uniq parses correctly , need include & before call.      print "\n";      print join('', sort( list::moreutils::uniq(split(//, lc $hello, 0)))); 

output :

   '?acdeiiinnstty  '?acdeinsty 

also tried how perl parses code b::deparse module , here output

perl -mo=deparse test.pl use list::moreutils ('uniq', 'distinct'); use warnings; use strict 'refs'; $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 warning when use uniq might clash future reserved keywords. useful links study list precedence , associativity helpful. referred perlop term , list operator section.

thanks in advance.

look @ docs sort. if pass sub name try use sorting.

that's why following 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 1 equivalent to:

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

the uniq function return 0 tests, claiming each character equal. therefore sort maintain same order, reducing above code just:

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

one trick keep sort using next sub comparator put + sign in front of sub name (ty mpapec):

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

Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -