Sort using a custom comparator: Difference between revisions

Content added Content deleted
m (→‎{{header|Perl}}: sundry clean-up)
Line 2,861: Line 2,861:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>use feature 'say';
{{works with|Perl|5.8.6}}
<lang perl>sub mycmp { length $b <=> length $a || lc $a cmp lc $b }


my @strings = ("Here", "are", "some", "sample", "strings", "to", "be", "sorted");
@strings = qw/Here are some sample strings to be sorted/;
my @sorted = sort mycmp @strings;</lang>


# with a subroutine:
Or inline:
sub mycmp { length $b <=> length $a || lc $a cmp lc $b }
<lang perl>my @strings = qw/here are some sample strings to be sorted/;
my @sorted = sort {length $b <=> length $a || lc $a cmp lc $b} @strings</lang>
say join ' ', sort mycmp @strings;


# inline:
Faster with a [[wp:Schwartzian transform|Schwartzian transform]]:
say join ' ', sort {length $b <=> length $a || lc $a cmp lc $b} @strings
<lang perl>my @strings = qw/here are some sample strings to be sorted/;

my @sorted = map { $_->[0] }
# for large inputs, can be faster with a 'Schwartzian' transform:
sort { $a->[1] <=> $b->[1] || $a->[2] cmp $b->[2] }
say join ' ', map { $_->[0] }
sort { $b->[1] <=> $a->[1] || $a->[2] cmp $b->[2] }
map { [ $_, length, lc ] }
map { [ $_, length, lc ] }
@strings;</lang>
@strings;</lang>
{{out}}
<pre>strings sample sorted Here some are be to
strings sample sorted Here some are be to
strings sample sorted Here some are be to</pre>


=={{header|Phix}}==
=={{header|Phix}}==