perl-hash

Perl:Access values of hash inside a hash

試著忘記壹切 提交于 2020-01-02 09:59:31
问题 I have just picked up Perl. I have a little confusion with accessing hash values. Below is the code where I am trying to access the values of a hash inside a hash. Since am using a simple text editor to code, I am not able to figure out what can be the problem. Please help my %box = ( Milk => { A => 5, B => 10, C => 20, }, Chocolate => { AB => 10, BC => 25, CD => 40, }, ); foreach my $box_key(keys %box) { foreach my $inside_key (keys %box{box_key}) print "$box_key"."_$inside_key""is for

How to sort perl hash on values and order the keys correspondingly (in two arrays maybe)?

南楼画角 提交于 2019-12-17 18:06:35
问题 In Perl, I want to sort the keys of a hash by value, numerically: { five => 5 ten => 10 one => 1 four => 4 } producing two arrays: (1,4,5,10) and (one, four, five, ten) And then I want to normalize the values array such that the numbers are sequential: (1,2,3,4) How do I do this? 回答1: First sort the keys by the associated value. Then get the values (e.g. by using a hash slice). my @keys = sort { $h{$a} <=> $h{$b} } keys(%h); my @vals = @h{@keys}; Or if you have a hash reference. my @keys =

How to sort perl hash on values and order the keys correspondingly (in two arrays maybe)?

孤者浪人 提交于 2019-11-28 06:22:55
In Perl, I want to sort the keys of a hash by value, numerically: { five => 5 ten => 10 one => 1 four => 4 } producing two arrays: (1,4,5,10) and (one, four, five, ten) And then I want to normalize the values array such that the numbers are sequential: (1,2,3,4) How do I do this? First sort the keys by the associated value. Then get the values (e.g. by using a hash slice). my @keys = sort { $h{$a} <=> $h{$b} } keys(%h); my @vals = @h{@keys}; Or if you have a hash reference. my @keys = sort { $h->{$a} <=> $h->{$b} } keys(%$h); my @vals = @{$h}{@keys}; How do I sort a hash (optionally by value