1

给定一系列名称标量(“Joe Hanson”、“James Rutherford McCoy”、“Thomas Jay Samuels”等),我如何按姓氏对它们进行排序?

我对 Perl(以及一般的脚本语言)有点陌生,似乎无法弄清楚这一点。

4

3 回答 3

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
于 2013-10-21T21:15:23.083 回答
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;
}
于 2013-10-21T21:01:45.307 回答
0

使用 Perl 的 split 函数拆分每个元素。我想你会想要类似的东西

@ary = split(/\s+/, $element);

然后抓住@ary.

http://perldoc.perl.org/functions/split.html

于 2013-10-21T20:52:10.420 回答