in reply to New-style sub strangeness

When you look at the output you get, you'll notice that sort foo(42) never calls foo. This is because Perl sees it as:

> perl -MO=Deparse -e "sub foo($); sort foo(42);" sort foo 42

... which means "sort the list with a single element '42' by using foo as the comparison operator".

If you use the "perl4" method of calling the subroutine (via &foo(...)), Perl knows what you really mean, but you could also tell this to Perl by adding a comma after the sort invocation, to tell sort that it gets a parameter list instead of a sort block:

> perl -MO=Deparse -e "sub foo($){44,33}; print for sort( foo(42), );" sub foo ($) { 44, 33; } ; print $_ foreach (sort foo(42)); > perl -wle "sub foo($){44,33}; print for sort( foo(42), );" 33 44

Replies are listed 'Best First'.
Re^2: New-style sub strangeness
by ChrisDennis (Sexton) on Jun 07, 2011 at 16:43 UTC
    Aha! The penny drops with regard to following 'sort' by the name of a subroutine. Thank you for all three answers. I didn't know about -MO=Deparse -- that could be very useful.

    cheers, Chris