[Date Prev][Date Next][Thread Prev][Thread Next]
[Search]
[Date Index]
[Thread Index]
Re: [FWP] Sort challenge
Lou Hevly wrote:
>
> Given the following data:
>
> __DATA__
> ae|Evans|Anne
> le|Evans|Louise
> he|Evans|Helen
> je|Evans|
> pete||Peter
> xs|Sanchez|
> rwj||
> est||
>
> 1) If there's a last name, the program should sort first by that and then by the firstname (if there is one);
> 2) If no last name, then sort by first name;
> 3) If neither last nor first name, then sort by username
>
> So the desired result is:
>
> est
> Evans
> Evans, Anne
> Evans, Helen
> Evans, Louise
> Peter
> rwj
> Sanchez
I'm not so happy with the first foreach-loop - but all attempts to circumvent it with map
{} have failed (predictably...).
Cheers,
-Christoph
#!/usr/bin/perl -w
use strict;
my @x;
my @y;
while (<DATA>) {
chomp;
push @x, [split /\|/];
}
foreach (@x){
my @c = @$_;
not $c[1] and ($c[1] = $c[0]);
push @y, \@c;
}
foreach (
sort {
(lc $y[$a][1] cmp lc $y[$b][1])
or
(lc $y[$a][2] cmp lc $y[$b][2])
or
(lc $y[$a][0] cmp lc $y[$b][0])
} 0..$#y
) {
($x[$_][1] and $x[$_][2]) ? print "$x[$_][1], $x[$_][2]"
:
($x[$_][1] ? print $x[$_][1]
:
($x[$_][2] ? print $x[$_][2]
: print $x[$_][0]));
print "\n";
}
__DATA__
ae|Evans|Anne
le|Evans|Louise
he|Evans|Helen
je|Evans|
pete||Peter
xs|Sanchez|
rwj||
est||
==== Want to unsubscribe from Fun With Perl? Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
==== unsubscribe