On Nov 30, 2003, at 12:33 PM, B. Rothstein wrote:
If I have a scalar variable that itslef is a list of names and numbers, for
example$names = 'john 35, jack 18, albert 24, timmy 42'; is it possible, and ifso how can it be done to separate the individual names and ages from the
list in their scalar form in order to create new lists sorted by names and
ages. thanks for any suggestions.
my @names = sort split /, ?/, $names;
this worked very well for the names only but did not sort properly for ages
as well
Okay, let's start with what you have. If we wanted to sort by name, then age, we could try:
my @names =
map { "$$_[0] $$_[1]" }
sort { $$a[0] cmp $$b[0] || $$a[1] <=> $$b[1] }
map { /^(.+?) (\d+)$/ && [ $1, $2 ] }
split /, ?/, $names;If you want to sort by age then name, reverse the two halves of the sort(). That's probably not very pretty but it's a variation of a common Perl idiom for sorting.
Now let's go back and rethink what you have now. How about making a hash? The name could be the key and the age the value.
my %ages = split /, ?/, $names;
From that it's trivial to do all kind of sorts:
my @name_sort = sort keys %ages;
my @age_sort = sort { $ages{$a} <=> $ages{$b} } keys %ages;
my @name_age_sort =
sort { $a cmp $b || $ages{$a} <=> $ages{$b} } keys %ages;Well, hopefully that gives you some ideas. Good luck.
James
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
