Reputation: 59
I'm quite new to perl and I need to find a way to sort hash. Many examples will run the sort then will just print to console. I need the new hash variable contain the key by sorted.
For example:
my %planets = (
Mercury => 0.4,
Venus => 0.7,
Earth => 1,
);
foreach my $name (sort keys %planets) {
printf "this $name \n";
}
I mean instead of printing I need to reference it back to another variable or even the %planets
itself.
So my expected final hash will be
%new_hash = (
Earth => 1,
Mercury => 0.4,
Venus => 0.7
);
Upvotes: 1
Views: 41
Reputation: 386206
You can't. There's no such thing as a sorted hash.
Nothing says you have to iterate over the result of sort
. You can store it in an array for later use.
my @sorted_keys = sort keys(%planets);
Another possibility is to convert the data structure you are using as you sort.
my @sorted_planets =
map { [ $_, $planets{$_} ] }
sort keys(%planets);
This produces:
my @sorted_planets = (
[ Earth => 1 ],
[ Mercury => 0.4 ],
[ Venus => 0.7 ],
);
Upvotes: 1