Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Hash Sorting

Status
Not open for further replies.

iono

Programmer
Oct 14, 2001
31
0
0
GB
Hi, I have a hash with this structure:

$users = {
$user => {
'id' => $idno,
'address' => $address,
'job' => $job,
}
}
id is a number.
(note: i simply wrote this to show the structure here, syntax errors in it are possible, it doesn't exist in the actual code).

What i want to do is loop through the hash with a foreach and display the users in decending id number order, but am not sure of how to go about it.
Thanks in advance, i'm not sure if i've included everything useful to this, so say if you need more information.
 
You need to generate for yourself a sorted list of keys to the [tt]%users[/tt] hash in the order that you want them presented. You can do this fairly easily with sort.

Code:
my @keys = sort { $b->{'id'} <=> $a->{'id'} } keys %users;
foreach my $key (@keys) { [COLOR=blue]display[/color] }

After doing the sort, [tt]@keys[/tt] is the keys of the [tt]%users[/tt] hash, ordered in decending order of the value of the [tt]{'id'}[/tt] key in the hash ref associated with that key.

Hope this helps.
 
best way I know (Schwartzian transform - beautiful and elegant if not a bit cryptic) - here goes;

my @new =

map {$_->[0]}
sort{$a->[1] <=> $b->[1]}
map{[$_, $hash->{$_}->{'id'}]} keys(%$users);

map {print $_ . &quot;\n&quot;;} @new;
 
Yes, I eventually found it out myself, it's working with greadey's method, and i'm sure rosenk's worsk aswell. Thanks for your time guys.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top