我有这组代码:
use strict;
use warnings;
my %hash = ( 5328 => 'Adorable',
26191 => '"Giraffe"',
57491 => 'Is Very',
4915 => 'Cute',);
foreach (sort { ($hash{$a} cmp $hash{$b}) || ($a cmp $b) } keys %hash)
{ print "$hash{$_}\n"; }
这将导致:
"Giraffe"
Adorable
Cute
Is Very
我需要按字母顺序排序,并忽略 AlphaNumeric 字符之前的特殊字符,如本示例中所示:
Adorable
Cute
"Giraffe"
Is Very
有什么建议?
最佳答案
您可以简单地这样做(请注意,我将第二个 cmp
更改为用于数值的穿梭运算符 <=>
):
foreach (sort { ($hash{$a}=~s/^\W+//r cmp $hash{$b}=~s/^\W+//r) || ($a <=> $b) } keys %hash) {
print "$hash{$_}\n";
}
但是如果你有很多数据,最好转换你的数据(一劳永逸):
例如使用施瓦兹变换:
my @result = map { $_->[2] }
sort { ($a->[0] cmp $b->[0]) || ($a->[1] <=> $b->[1]) }
map { [ $hash{$_}=~s/^"|"$//gr, $_, $hash{$_}] } keys %hash;
print join "\n", @result;
关于regex - 带有特殊字符的字母顺序 perl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41557647/