in reply to Prototype like sort()?

FWIW, this is an implementation in Perl of an exotic sort algorithm, comb sort (or Dobosiewicz's sort - see https://en.wikipedia.org/wiki/Comb_sort for details), using prototypes to mimic Perl's internal sort function:
sub comb_sort (&\@) { my $code_ref = shift; my $v_ref = shift; my $max = scalar (@$v_ref); my $gap = $max; while (1) { my $swapped = 0; $gap = int ($gap / 1.3); $gap = 1 if $gap < 1; my $lmax = $max - $gap - 1; foreach my $i (0..$lmax) { local ($a, $b) = ($$v_ref[$i], $$v_ref[$i+$gap]); ($$v_ref[$i], $$v_ref[$i+$gap], $swapped) = ($$v_ref[$i+$g +ap], $$v_ref[$i], 1) if $code_ref->($a, $b) > 0; } last if $gap == 1 and $swapped == 0; } }
This sort subroutine can be called with a code block just as Perl's internal sort. For example:
#!/usr/bin/perl use strict; use warnings; my @v; my $max = 500; $v[$_] = int rand(20000) foreach (0..$max); comb_sort {$a<=>$b} @v; print "@v";
I'm not sure that's what you're after, but you can see above a calling syntax with a simple code block (no need to build an actual subroutine).

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

    Yup, not quite. sort can be called without a block, while using the & prototype means your sub has to be called with a block. Perhaps if Perl supported a prototype like [&@$] like it does \[&@$].

      Yes, right, this syntax allows only the block syntax, not the expression syntax. And I don't think there is any simple way to enable an expression syntax for such a sort subroutine (or for a custom clone of the map or grep functions).

      But that does not deprive you of any functionality: any sort construct using the sort expression syntax can be easily transformed into a block syntax, essentially by adding a pair of curly brackets and removing the comma.