我有这样的字符串:
"PQR23 on abc62", "PQR112 on efg7", "PQR9 on efg76" and so on
现在我想把这个字符串按第一个字符的数字升序排列。
所以预期的输出应该是
PQR112 on efg7
PQR23 on abc62
PQR9 on efg76
等等
我是 perl 新手,在网上做作业和搜索,但到目前为止还没有收到完美的解决方案。谢谢。
I am not sure what you want that a simple lexical sort doesn't provide. The program belows seems to do what you have specified.
use strict;
use warnings;
my @strings = (
"PQR23 on abc62",
"PQR112 on efg7",
"PQR9 on efg76",
);
print "$_\n" for sort @strings;
output
PQR112 on efg7
PQR23 on abc62
PQR9 on efg76
Edit
If you want to ignore the prefix letters, then a code block for sort will do the trick
use strict;
use warnings;
my @strings = (
"ABC23 on abc62",
"PQR112 on efg7",
"XYZ9 on efg76",
);
print "$_\n" for sort {
my ($aa) = $a =~ /(\d)/;
my ($bb) = $b =~ /(\d)/;
$aa cmp $bb;
} @strings;
output
PQR112 on efg7
ABC23 on abc62
XYZ9 on efg76
You could also use Schwartzian Transform like that, very efficient if your array is big:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my @strings = (
"PQR23 on abc62",
"PQR112 on efg7",
"PQR9 on efg76",
);
my @result =
map { $_->[0] }
sort { $a->[1] <=> $b->[1]}
map { [$_, /(\d)/] }
@strings;
print Dumper\@result;
output:
$VAR1 = [
'PQR112 on efg7',
'PQR23 on abc62',
'PQR9 on efg76'
];
use strict;
use warnings;
my @sorted_strings=sort("PQR23 on abc62", "PQR112 on efg7", "PQR9 on efg76");
print join ("\n",@sorted_strings);
输出
PQR112 on efg7
PQR23 on abc62
PQR9 on efg76