At 09:15 AM 6/16/2001 -0700, Ron Anderson wrote:
>Hi!
>
>Using the following hash as an example:
>
>$shash{"student1"} = join("\t", ("bob", "tyson", "room5"));
>$shash{"student2"} = join("\t", ("ron", "anderson", "room4"));
>$shash{"student3"} = join("\t", ("dave", "lee", "room2"));
>$shash{"student4"} = join("\t", ("tim", "barker", "room3"));
>$shash{"student5"} = join("\t", ("roger", "farley", "room1"));
>
>How can I sort the hash by, for example, last name?
>
>And can I sort the hash by last name and then first name?
>
>I've learned to sort by the key or by the entire value, but sorting by a
>single element escapes me.
Well, part of the problem is that your hash values are not multiple
elements; they are single elements with embedded tab characters. That
makes the sorting a bit harder:
# Sort by last name:
sub last_name { (split/\t/,shift)[1] }
@keys = sort { last_name($shash{$a}) cmp last_name($shash{$b}) } keys %shash;
# Sort by last name then first name:
sub first_name { (split/t/, shift)[0] }
@keys = sort { last_name($shash{$a}) cmp last_name($shash{$b})
or first_name($shash{$a}) cmp first_name($shash{$b})
} keys %shash;
In each case, of course, you're getting the keys of the hash.
Consider using instead a hash-of-hashes or hash-of-arrays(perldoc perllol).