Sort using a custom comparator: Difference between revisions

m
→‎{{header|Perl}}: sundry clean-up
m (→‎{{header|Perl}}: sundry clean-up)
Line 2,861:
 
=={{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 = ("qw/Here", "are", "some", "sample", "strings", "to", "be", "sorted")/;
my @sorted = sort mycmp @strings;</lang>
 
# with a subroutine:
Or inline:
<lang perl>sub mycmp { length $b <=> length $a || lc $a cmp lc $b }
<lang perl>my @strings = qw/here are some sample strings to be sorted/;
mysay @sortedjoin =' ', sort {length $b <=> length $a || lc $a cmp lc $b}mycmp @strings</lang>;
 
Or# 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] }
mysay @sortedjoin =' ', map { $_->[0] }
sort { $ab->[1] <=> $ba->[1] || $a->[2] cmp $b->[2] }
map { [ $_, length, lc ] }
@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}}==
2,392

edits