"What would I use one of
THOSE for?" - a question often asked by newcomers to Perl when I first introduce hashes. Well - in writing a script to count up how many articles I've written about each subject we teach on, I came up with a perfect example.
A
hash is described as an "unordered collection" variable. That means that under one name, you can hold a whole lot of values just as you can in a list or an array - but you can key the elements by name not by position number. Consider the TWO lists:
1 | England |
2 | Scotland |
3 | Wales |
4 | Northern Ireland |
5 | Ireland |
and
1 | London |
2 | Edinbugh |
3 | Cardiff |
4 | Belfast |
5 | Dublin |
Using those two lists, I could find you the capital of a country by searching through the first list, and looking up the value at that position number in the second list. But wouldn't it be easier if I could just use a single table?:
England | London |
Scotland | Edinburgh |
Wales | Cardiff |
Northern Ireland | Belfast |
Ireland | Dublin |
And that's exactly what a hash lets you do. No need to search. No need to have (artificial) position numberings. No need to be VERY careful to keep the two lists syncronised as you edit them.
Here's some code from the example I wrote this morning. Firstly, here's how I set up a hash, keyed by the modules, to count the number of times each is mentioned in my data file:
open FH, "/home/wellho/ include /bloglinks.txt";
while (<FH>) {
chop;
($ref,$mod) = split;
$counter{$mod}++;
}
Here's another example of setting up a hash, this time reading the name of each module from a file:
open FH, "/home/wellho/ public_html /resources/mtable.txt" ;
while (<FH>) {
chop;
($ref,$about) = split(/\s+/,$_,2);
$lookup{$ref} = $about;
}
And then I printed out the results:
print "\nHow many times have I talked about THAT?\n";
for (sort {$counter{$a} <=> $counter{$b}} keys(%counter)) {
print "$_ - $counter{$_} - $lookup{$_}\n";
}
Of course, I wanted the results in order. And the irony is that you
cannot sort a hash. But you
can get a list of all of the keys, and then sort that list - and that's what I've done. The results:
How many times have I talked about THAT?
[snip]
G102 - 34 - Things to do in Melksham
H108 - 35 - Objects in PHP
H115 - 35 - Designing PHP-Based Solutions: Best Practice
M100 - 36 - Introduction to Well House Manor
A603 - 38 - Further httpd Configuration
H999 - 38 - Additional PHP Material
A101 - 41 - Linux -An Introduction For Users
M401 - 42 - Seeing how others do it
G999 - 42 - Keynote
H112 - 42 - Further Web Page and Network Handling
Y105 - 43 - Functions, Modules and Packages
Z511 - 43 - Public Transport - Road
M300 - 43 - Behind the scenes
[snip]
Isn't that great, short code? You can read more articles about hashes in Perl
[here]. And the concept is so good you'll also find it used in Python's dictionaries
[here], Ruby's hashes
[here], Tcl's Arrays
[here], Lua'a tables
[here] and PHP's associative arrays
[here]. In C, C++ and Java, you'll find the same structures available to you through libraries; in Java, they're the HashMap, HashSet and Hash within the java.util package - see
[here].
The complete source code of the Perl examples is
[here], and I've enclosed it in a CGI wrapper so that you can run it
[here]. Well, actually that's to let
me run it, as it's a useful reminder of what I haven't talked about in a while.
Want to learn more Perl? See our
Perl Courses.
Pictures - Cardiff, Edinburgh, London, Dublin and Belfast - which is which?
(written 2011-09-20)
Associated topics are indexed as below, or enter http://melksh.am/nnnn for individual articles
Q110 - Object Orientation and General technical topics - Programming Algorithms [202] Searching for numbers - (2005-02-04)
[227] Bellringing and Programming and Objects and Perl - (2005-02-25)
[642] How similar are two words - (2006-03-11)
[1157] Speed Networking - a great evening and how we arranged it - (2007-04-21)
[1187] Updating a page strictly every minute (PHP, Perl) - (2007-05-14)
[1391] Ordnance Survey Grid Reference to Latitude / Longitude - (2007-10-14)
[1840] Validating Credit Card Numbers - (2008-10-14)
[1949] Nuclear Physics comes to our web site - (2008-12-17)
[2189] Matching disparate referencing systems (MediaWiki, PHP, also Tcl) - (2009-05-19)
[2259] Grouping rows for a summary report - MySQL and PHP - (2009-06-27)
[2509] A life lesson from the accuracy of numbers in Excel and Lua - (2009-11-21)
[2586] And and Or illustrated by locks - (2010-01-17)
[2617] Comparing floating point numbers - a word of caution and a solution - (2010-02-01)
[2894] Sorting people by their names - (2010-07-29)
[2951] Lots of way of converting 3 letter month abbreviations to numbers - (2010-09-10)
[2993] Arrays v Lists - what is the difference, why use one or the other - (2010-10-10)
[3042] Least Common Ancestor - what is it, and a Least Common Ancestor algorithm implemented in Perl - (2010-11-11)
[3072] Finding elements common to many lists / arrays - (2010-11-26)
[3093] How many toilet rolls - hotel inventory and useage - (2010-12-18)
[3102] AND and OR operators - what is the difference between logical and bitwise varieties? - (2010-12-24)
[3620] Finding the total, average, minimum and maximum in a program - (2012-02-22)
[3662] Finding all the unique lines in a file, using Python or Perl - (2012-03-20)
[4325] Learning to program - what are algorithms and design patterns? - (2014-11-22)
[4401] Selecting RECENT and POPULAR news and trends for your web site users - (2015-01-19)
[4402] Finding sum, minimum, maximum and average in Python (and Ruby) - (2015-01-19)
[4410] A good example of recursion - a real use in Python - (2015-02-01)
[4652] Testing new algorithms in PHP - (2016-02-20)
[4656] Identifying the first and last records in a sequence - (2016-02-26)
[4707] Some gems from an introduction to Python - (2016-10-29)
P211 - Perl - Hashes [240] Conventional restraints removed - (2005-03-09)
[386] What is a callback? - (2005-07-22)
[738] (Perl) Callbacks - what are they? - (2006-05-30)
[930] -> , >= and => in Perl - (2006-11-18)
[968] Perl - a list or a hash? - (2006-12-06)
[1334] Stable sorting - Tcl, Perl and others - (2007-09-06)
[1705] Environment variables in Perl / use Env - (2008-07-11)
[1826] Perl - Subs, Chop v Chomp, => v , - (2008-10-08)
[1856] A few of my favourite things - (2008-10-26)
[1917] Out of memory during array extend - Perl - (2008-12-02)
[2833] Fresh Perl Teaching Examples - part 2 of 3 - (2010-06-27)
[2836] Perl - the duplicate key problem explained, and solutions offered - (2010-06-28)
[2915] Looking up a value by key - associative arrays / Hashes / Dictionaries - (2010-08-11)
[2920] Sorting - naturally, or into a different order - (2010-08-14)
[3106] Buckets - (2010-12-26)
[3400] $ is atomic and % and @ are molecular - Perl - (2011-08-20)
Some other Articles
MySQL, MySQLi, PDO or something else - how best to talk to databases from PHPYour PHP website - how to factor and refactor to reduce growing painsReading and using emails including enclosures on your web server.Which or ATOC - who reads train fares right?Why would you want to use a Perl hash?A threat in the post? Poor marketing practise from Smiletrain?Apache Internal Dummy Connection - what is it and what should I do with it?Checking all the systems on a subnet, using Expect and TkNeedle in a haystack - finding the web server overloadAwk v Perl