develooper Front page | perl.beginners | Postings from February 2002

Re: sort on anonymous array elements as hash values

Thread Previous
From:
Brett W. McCoy
Date:
February 6, 2002 08:58
Subject:
Re: sort on anonymous array elements as hash values
Message ID:
Pine.LNX.4.43.0202061205180.14577-100000@chapelperilous.net
On Wed, 6 Feb 2002, birgit kellner wrote:

> my %hash = (
> 	'keyone' => ['firstvalueone', 'firstvaluetwo],
> 	'secondkey' => ['anothervalueone', 'valuetwoforsecondkey'],
> 	'keythree' => ['thirdvalueone', 'thirdvaluetwo']
>
> );
>
> Can I sort the hash on the second element of the anonymous array?

Sure, use the sort function:

#!/usr/local/bin/perl -w

use strict;

my %hash = (
        'keyone' => ['firstvalueone', 'firstvaluetwo'],
        'secondkey' => ['anothervalueone', 'valuetwoforsecondkey'],
        'keythree' => ['thirdvalueone', 'thirdvaluetwo']

);


my @result = sort {$hash{$a}->[1] cmp $hash{$b}->[1]} keys %hash;

foreach(@result) {

	print "$hash{$_}->[1]\n";
}

Which prints out:

~$ ./sortme.pl
firstvaluetwo
thirdvaluetwo
valuetwoforsecondkey

-- Brett
                                          http://www.chapelperilous.net/
------------------------------------------------------------------------
bug, n:
	A son of a glitch.


Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About