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

Re: [FWP] Sort challenge



Lou Hevly <lou@visca.com> wrote:
> 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
>


Two solutions, one with 102 characters and the other with 89. (Can it be
smaller?) Both expect to receive the file with the data as arguments,
instead of __DATA__, but changing <> to <DATA> would make it work with
__DATA__.


    ($u,$l,$f)=split(/[|\n]/),push@a,$l?$f?"$l, $f":$l:$f||$u
    while<>;$,=$\=$/;print sort{lc$a cmp lc$b}@a


    $,=$\=$/,print
    sort{lc$a cmp lc$b}map{($u,$l,$f)=split/[|\n]/;$l?$f?"$l,
    $f":$l:$f||$u}<>


I've replaced space " " with a carriage return (with some spaces after it),
so that it fits in the mail message. do s/\n    / /g before running them.
The first one (the longer one) will run ok without doing it, but the second
needs it to format "Last, First" properly.

[[ BTW, what's the best way to send these long lines of perl code in mail
messages? ]]

Hope you like it.

- Branden


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