in reply to implicit sort disables a chained subroutine?

The sub is being used as a comparitor. See the documentation for sort SUBNAME LIST

#! perl -slw use strict; $a=$b='unused'; sub uniq { print "unique($a,$b):",@_; my %x; @x{@_} = (); keys %x } my @array = ( 'A' .. 'Z', reverse 'A' .. 'Z' ); ## Explicit sort block works as expected print sort { $a cmp $b } uniq @array; ## uniq is used a comparator here print sort uniq @array; __DATA__ unique(unused,unused):ABCDEFGHIJKLMNOPQRSTUVWXYZZYXWVUTSRQPONMLKJIHGFE +DCBA ABCDEFGHIJKLMNOPQRSTUVWXYZ unique(A,B): unique(C,D): unique(E,F): <SNIP> unique(K,J): unique(I,H): unique(G,F): unique(E,D): unique(C,B): ABCDEFGHIJKLMNOPQRSTUVWXYZZYXWVUTSRQPONMLKJIHGFEDCBA

You need to use the full ampersand and brackets to avoid it.

#! perl -slw use strict; sub uniq { my %x; @x{@_} = (); keys %x } my @array = ( 'A' .. 'Z', reverse 'A' .. 'Z' ); ## Explicit sort block works as expected print sort { $a cmp $b } uniq @array; ## must use &sub(@args); here or uniq is used as a comparator. print sort &uniq(@array); __DATA__ ABCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXYZ
---
demerphq

Replies are listed 'Best First'.
Re^2: implicit sort disables a chained subroutine?
by BrowserUk (Patriarch) on Jan 13, 2005 at 21:09 UTC

    Thanks. That's the explanation that clinches it for me.

    I guess the distinction between using a built-in that returns a list, in a chain:

    print sort split'', $string;

    which works, and using a user sub which produces a list, in the same place:

    print sort uniq @array;

    which doesn't, is just another anomoly caused by the DWIMery of builtins.


    Examine what is said, not who speaks.
    Silence betokens consent.
    Love the truth but pardon error.