[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

[FWP] Sort challenge



Greetings all:

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

Here is my own rather kludgy solution:

#!/usr/bin/perl -w
use strict;

my %h;
while (<DATA>) {
  chomp;
  my($u, $l, $f) = (split /\|/);
  for my $v ( $l, $f, $u ) {
    next unless $v;
    $h{$u} = [ $v, [split /\|/] ];
    last;
  }
}

for (
  sort { 
        lc $h{$a}[0] cmp lc $h{$b}[0] 
                     ||
     lc $h{$a}[1][2] cmp lc $h{$b}[1][2] 
        } 
   keys %h
   ) {

  if ($h{$_}[1][1]) { # the last name
    print $h{$_}[1][1];
    $h{$_}[1][2] ? print ", $h{$_}[1][2]\n" : print "\n";
    next;
  }
  elsif ($h{$_}[1][2]) { # the first name
    print "$h{$_}[1][2]\n";
    next;
  }
  else {
    print "$h{$_}[1][0]\n"; # the username
  }
}

__DATA__
ae|Evans|Anne
le|Evans|Louise
he|Evans|Helen
pete||Peter
xs|Sanchez|
rwj||
est||
-- 
All the best (Adéu-siau),
Lou Hevly
lou@visca.com
http://www.visca.com


==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe