hash order perl
Help with a basic perl program?
I have an assignment for one of my classes, basic perl stuff. I need to write a small perl program that writes 5 baseball players to a hash with their names and number of home runs. Then I’m supposed to have it print out the players and the # of homeruns, one per line. After that, I need to sort it in alphabetical order. I have two questions: 1. how do I get it to print the values out, and 2. how do I sort it in alpha order. Thanks in advance!
1. To print the values, use the foreach loop with each hash item referred by keys. example:
foreach my $name ( keys %hash ) { … }
2. To sort the names use the sort keyword before the keys keyword:
foreach my $name ( sort keys %hash ) { … }
Tip: sort keyword is used to sort alphabetically. If you want to sort numbers, then you need to explicitly write as
foreach my $num ( sort { $a <=> $b } keys %hash ) { … }
note that the code in #2 can also be written as
foreach my $name ( sort { $a cmp $b } keys %hash ) { … }
both are synonymous
Sack 0.07 – sharding memory hash in perl