鉴于一系列名称标量(“Joe Hanson”,“James Rutherford McCoy”,“Thomas Jay Samuels”等等),我如何按姓氏排序?
我对Perl(以及一般的脚本语言)有点新意,似乎无法解决这个问题。
答案 0 :(得分:5)
看起来像Schwartzian变换的工作(假设其他人有最后一个字符串是姓氏):
#!/usr/bin/perl
use warnings;
use strict;
my @names = ( 'Joe Hanson', 'James Rutherford McCoy', 'Thomas Jay Samuels', 'Joe Johnson', 'Tim McGee', 'The Reverend Horton Heat');
my @sorted_names =
map { $_->[0] }
sort { $a->[1] cmp $b->[1] }
map { [$_, /(\w+)$/] } @names;
print "$_\n" for @sorted_names;
运行此命令将导致:
Joe Hanson
The Reverend Horton Heat
Joe Johnson
James Rutherford McCoy
Tim McGee
Thomas Jay Samuels
答案 1 :(得分:1)
#!/usr/bin/perl
use strict;
use warnings FATAL => qw/all/;
use Data::Dumper;
my @names = ("Joe Hanson", "James Rutherford McCoy", "Thomas Jay Samuels");
my @sorted_names = sort bylastname @names;
print Dumper \@sorted_names;
sub bylastname
{
my $lastname_regexp = qr/(\w+)$/;
my ($a_lastname) = $a =~ $lastname_regexp;
my ($b_lastname) = $b =~ $lastname_regexp;
$a_lastname cmp $b_lastname;
}
答案 2 :(得分:0)
使用Perl拆分功能拆分每个元素。我想你会想要类似的东西
@ary = split(/\s+/, $element);
然后抓住@ary
的最后一个元素。