SPUG: Another stupid question, hash sorting

Jonathan Mark jhmark at xenops.com
Tue Jul 2 18:40:17 CDT 2002


On Tue, 2 Jul 2002, Peter Darley wrote:
> 	Specifically I have a hash containing {Score} and {Name} values, and I want
> to primarily sort on score, and sort on name where the score is the same.

yes, as Ben said ... you can provide a comparison function to sort on.
An example follows.

best,

	Jonathan

sub by_score_and_name
{
    my $score_cmp = $a->{Score} <=> $b->{Score};
    return $score_cmp if $score_cmp != 0;
    return $a->{Name} cmp $b->{Name};
}

my @a = ({Score => 5, Name => 'ann'},
	 {Score => 5, Name => 'the other ann'},
	 {Score => 2, Name => 'lars'});

my @sorted = sort by_score_and_name @a;


 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
      Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
  Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
 For daily traffic, use spug-list for LIST ;  for weekly, spug-list-digest
     Seattle Perl Users Group (SPUG) Home Page: http://seattleperl.org




More information about the spug-list mailing list