03/01/2003: Sorting Perl Hashes by Keys and by Values
Sorting Perl Hashes by Keys and by Values
Code
#/usr/bin/perl -w use strict; my(%hash); # Create a hash with four elements. $hash{'01'} = 'D'; $hash{'02'} = 'C'; $hash{'03'} = 'B'; $hash{'04'} = 'A'; # Sort the hash according to its keys. my(@sortedByKey) = sort(keys(%hash)); # Print out the hash entries in sorted order. print "Sorted by Key:\n"; foreach (@sortedByKey) { print "\t$_: $hash{$_}\n"; } # Sort the hash according to its keys. The # $a and $b scalars are part of the main # package namespace. Therefore, the main # package name needs to be specified when # using the strict pragma. my(@sortedByValue) = sort { $hash{$main::a} cmp $hash{$main::b} } keys %hash; # Print out the hash entries in sorted order. print "Sorted by Value:\n"; foreach (@sortedByValue) { print "\t$_: $hash{$_}\n"; }
output
Sorted by Keys: 01: D 02: C 03: B 04: A Sorted by Values: 04: A 03: B 02: C 01: D
03/01/2003: Using Hashes in Bash Scripts
Using Hashes in Bash Scripts
This codebit was donated by Phil Howard on 1998Dec03. Hash data structures are very convenient. They let you use strings as indexes instead of numbers. The value
script, shown below, demonstrates how to use Bash's eval command to simulate a hash structure. The command, value david
prints "The email address for david is medined@mtolive.com"
.
#!/bin/bash # value.sh email_phil="phil@rigel.ipal.net" email_david="medined@mtolive.com" eval 'email=${email_'"${1}"'}' echo "The email address for ${1} is ${email}"