jake9115
jake9115

Reputation: 4084

Alphabetizing a list of hash keys in perl?

I want to make an array that stores an alphabetized list of hash keys. I tried this method:

@sorted = sort { $hash{$a} cmp $hash{$b} } keys %hash; 

...But it turns out this returns a list of hash keys sorted by value (whereas I want a list of hash keys sorted alphabetically).

Any suggestions?

Upvotes: 1

Views: 1331

Answers (3)

jaypal singh
jaypal singh

Reputation: 77095

foreach my $key ( sort {$a cmp $b} keys %hash) {

# do something ..

}

Upvotes: 1

ikegami
ikegami

Reputation: 385657

my @sorted = sort { $a cmp $b } keys %hash;

or just

my @sorted = sort keys %hash;

Upvotes: 11

chepner
chepner

Reputation: 531065

Hash keys are just strings:

@sorted = sort keys %hash;

Upvotes: 3

Related Questions