Click to See Complete Forum and Search --> : Sorting a list?


johnn
04-09-2003, 05:14 AM
is it possible to display names from a plain txt file and sort them alphabetically by surname? or just alphabetically as they stand? They are stored in a text file like so:

John Smith
Joe Brown
Ben Straw

Thanks.

jeffmott
04-09-2003, 03:52 PM
You can sort them however you wish, after a little manipulation. I might go about it like this:use strict;
use warnings FATAL => 'all';

chomp(my @names = <DATA>);
my %names;

for (@names) {
my($fn, $ln) = split;
push @{$names{$ln}}, $fn;
}

undef @names;

for my $ln (sort keys %names) {
push @names, "$_ $ln" for sort @{$names{$ln}};
}

print join("\n", @names);

__DATA__
John Smith
Joe Brown
Ben Straw