Mohamed Afiq
Mohamed Afiq

Reputation: 59

Perl sort hash and overwrites/add to new variable

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

Answers (1)

ikegami
ikegami

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

Related Questions