http://www.perlmonks.org?node_id=1208252


in reply to Re: Prototype like sort()?
in thread Prototype like sort()?

I'm a bit late to the party, I just wanted to point out that it's not impossible to have one sub do it all, just ugly (and with the limitation that in the third form, the first thing in the list can't be a coderef):

sub mysort (&@) { my $sub = ref $_[0] eq 'CODE' ? shift : sub {...}; ... } sub subname {...}; mysort {...} 'x', 'y', 'z'; mysort \&subname, 'x', 'y', 'z'; &mysort( 'x', 'y', 'z');

On the other hand, I like your solution of rank @list vs. rankby {...} @list!

Replies are listed 'Best First'.
Re^3: Prototype like sort()?
by LanX (Saint) on Feb 01, 2018 at 19:13 UTC
    Unfortunately there is an ugly and hard to debug edge case when using an &call with an empty list.

    From perlsub

    &foo;        # foo() get current args, like foo(@_) !!

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Wikisyntax for the Monastery

Re^3: Prototype like sort()?
by LanX (Saint) on Feb 01, 2018 at 17:13 UTC
    Nice!

    to elaborate further, the trick you are using is that prepending & to a sub let's the parser ignore the prototype.

    > perlsub: Not only does the & form make the argument list optional, it also disables any prototype checking on arguments you do provide. This is partly for historical reasons, and partly for having a convenient way to cheat if you know what you're doing. 

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Wikisyntax for the Monastery

Re^3: Prototype like sort()?
by perlancar (Hermit) on Feb 05, 2018 at 05:11 UTC

    Yup, all the time I write subs that behave differently depending on the type of arguments. The most common is: foo([ \%opts ], $arg, ...) and then trying to detect the optional hashref in the first argument.

    What I'm looking for here is the syntax bonus :)