是的。
sort
可以采用任何返回相对排序位置的函数。所有你需要的是一个函数,可以正确查找字符串的“排序值”进行比较。
所以你所需要做的就是定义你的多余字母的“相对权重”,然后比较两者。
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
my @sort_order = qw (B C A D);
my @array_to_sort = qw (A B C D A B C D AB BB CCC ABC);
my $count = 0;
my %position_of;
$position_of{$_} = $count++ for @sort_order;
print Dumper \%position_of;
sub sort_by_pos {
my @a = split //, $a;
my @b = split //, $b;
#iterate one letter at a time, using 'shift' to take it off the front
#of the array.
while (@a and @b) {
my $result = $position_of{shift @a} <=> $position_of{shift @b};
#result is 'true' if it's "-1" or "1" which indicates relative position.
# 0 is false, and that'll cause the next loop iteration to test the next
#letter-pair
return $result if $result;
}
#return a value based on remaining length - longest 'string' will sort last;
#That's so "AAA" comparing with "AA" comparison actually work,
return scalar @a <=> scalar @b;
}
my @new = sort { sort_by_pos } @array_to_sort;
print Dumper \@new;
一个简单的案例一点,但排序数组到:
$VAR1 = [
'B',
'B',
'BB',
'C',
'C',
'CCC',
'A',
'A',
'AB',
'ABC',
'D',
'D'
];
你上面的代码是正确的,你只需要实现by_my_alphabet。查看这里使用自定义比较器演示的示例:https://perldoc.perl.org/functions/sort.html – Floegipoky