in reply to Prototype like sort()?

There are a whole bunch of reasons to not use prototypes. But a simple example of something that I don't recommend...
#!/usr/bin/perl use warnings; use strict; sub mysort (@) { my @array = @_; return sort @array; } my @abc = mysort 4,2,1,3; print "@abc"; #prints 1 2 3 4

Replies are listed 'Best First'.
Re^2: Prototype like sort()?
by perlancar (Hermit) on Jan 25, 2018 at 10:03 UTC

    That doesn't allow mysort() to accept coderef without the "sub" like sort() does:

    mysort {$b<=>$a} 4,2,1,3; # syntax error
      Ok, fair enough. I am beginning to understand your question, but I'm not there yet. $a and $b are special variables that Perl uses.

      This can't be simply about sort. Perhaps, can you explain more specifically about what you want?

        While I would not recommend it, $a and $b are only special in that they are predeclared and used by sort. Otherwise, you can use them like any other package variable:

        sub mysort (&@) { my $coderef = shift; while (@_ > 1) { $a = shift; $b = $_[0]; my $c = $coderef->(); print " $c"; # do sorting } print "\n"; } mysort { $a <=> $b } qw(1 3 2);

        But, it is a bad idea to use $a and $b except with sort

        But, could use 2 other variables. Just have to declare them.

Re^2: Prototype like sort()?
by karlgoethebier (Abbot) on Jan 27, 2018 at 17:54 UTC
    "...a whole bunch of reasons to not use prototypes..."

    Yes, may be. But some cool modules do it all the time - e.g.:

    sub apply (&@) { my $action = shift; &$action foreach my @values = @_; wantarray ? @values : $values[-1]; }

    Best regards, Karl

    «The Crux of the Biscuit is the Apostrophe»

    perl -MCrypt::CBC -E 'say Crypt::CBC->new(-key=>'kgb',-cipher=>"Blowfish")->decrypt_hex($ENV{KARL});'Help