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

Re: [MacPerl] sorting arrays



On Wed, 16 Jun 1999 09:21:16 -0400, cetasix@pop.erols.com wrote:

>It does not seem to work. Is there something I'm missing in the code?

Of course it doesn't work. You're reading in one line, sorting that
array of one line (currently, you're sorting first and last name), and
printing out the result. Then you go to the next line...

Read in in ALL lines from the file. THEN try to sort them. Besides, your
file opening statement is very fishy. In short: drop the "if", and
associated block delimiters.

I've written the code using a Schwartzian transform, i.e. "map sort
map". The odd thing about this, is that the execution order is reversed
from the reading/writing order, so you have to start reading it from the
far right (last line).

#! perl -w
@sorted = map { "$_->[0], $_->[1]" } # combine last and first name
    sort { $a->[0] cmp $b->[0]  # last name; but, if equal:
        || $a->[1] cmp $b->[1]  # first name
    } map { chomp; [ split /\|\|/ ] } # convert to anonymous array: 
					# [ "last name", "first name" ]
    <DATA>; # for each line read
#printout:
$, = "\n"; $\ = "\n";
print @sorted;

__DATA__
Janssen||Willem
Hinders||Trintje
Beving||John
Beving||Henrietta
Beving||Ubbe
Beving||Henry
Beving||Henry
Beving||Etta
Beving||Minnie
Beving||Bertha
Willemssen||male
Willemssen||male
Willemssen||Wopka(e)
Brower||Coba
Brower||John
Brower||Bertha

	Bart.

===== Want to unsubscribe from this list?
===== Send mail with body "unsubscribe" to macperl-request@macperl.org