user2268507
user2268507

Reputation:

Printing perl hash keys and values sorted by value

I have ordered my hashmap by value and am printing them. After printing the value, I would like to print the corresponding key.

My code is currently:

foreach my $value (sort (values %student_id_name_hash)){
   print "$value\n";
   // Print correspnding key here
}

I am trying to print unique student IDs (keys) and corresponding student names (values), which may not be unique.

A method was suggested here that involved reverse but depends on the values being unique: http://www.perlmonks.org/?node_id=177969

Is this the best way to go about it? There is no guarantee that the values will be unique in my case.

Upvotes: 2

Views: 3033

Answers (2)

AnFi
AnFi

Reputation: 10903

You can sort keys based on values associated with them

# standard good practice pragmas
use strict; use warnings; use utf8;

# sample/test data
my %id_hash = (
  X1 => 'Smith, Jane',
  Z9 => 'Doe, John',
);

# sort keys based on value and print
foreach my $key (sort {$id_hash{$a} cmp $id_hash{$b}} keys %id_hash ){
  my $value = $id_hash{$key};
  print "$value\n  $key\n";
}

Upvotes: 0

Miller
Miller

Reputation: 35198

If you want the keys as well as values, then you need to iterate based off of the keys and sort based off the value, like so:

for my $key ( sort { $student_id_name_hash{$a} cmp $student_id_name_hash{$b} }
    keys %student_id_name_hash )
{
    print "$key - $student_id_name_hash{$key}\n";
}

Upvotes: 2

Related Questions