Training, Open Source Computer Languages

This is page http://www.wellho.net/mouth/3451_Why ... hash-.html

Our email: info@wellho.net • Phone: 01144 1225 708225

Why would you want to use a Perl hash?

"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.

Cathays Station, CardiffA 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:

1England
2Scotland
3Wales
4Northern Ireland
5Ireland


and


Guess where - it was - Dublin
1London
2Edinbugh
3Cardiff
4Belfast
5Dublin


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?:


Sculpture
EnglandLondon
ScotlandEdinburgh
WalesCardiff
Northern IrelandBelfast
IrelandDublin


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.


Edinburgh CastleHere'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:


London from Aldgate Hotel  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
P211 - Perl - Hashes
  [3662] Finding all the unique lines in a file, using Python or Perl - (2012-03-20)
  [3400] $ is atomic and % and @ are molecular - Perl - (2011-08-20)
  [3106] Buckets - (2010-12-26)
  [3072] Finding elements common to many lists / arrays - (2010-11-26)
  [3042] Least Common Ancestor - what is it, and a Least Common Ancestor algorithm implemented in Perl - (2010-11-11)
  [2920] Sorting - naturally, or into a different order - (2010-08-14)
  [2915] Looking up a value by key - associative arrays / Hashes / Dictionaries - (2010-08-11)
  [2836] Perl - the duplicate key problem explained, and solutions offered - (2010-06-28)
  [2833] Fresh Perl Teaching Examples - part 2 of 3 - (2010-06-27)
  [1917] Out of memory during array extend - Perl - (2008-12-02)
  [1856] A few of my favourite things - (2008-10-26)
  [1826] Perl - Subs, Chop v Chomp, => v , - (2008-10-08)
  [1705] Environment variables in Perl / use Env - (2008-07-11)
  [1334] Stable sorting - Tcl, Perl and others - (2007-09-06)
  [968] Perl - a list or a hash? - (2006-12-06)
  [930] -> , >= and => in Perl - (2006-11-18)
  [738] (Perl) Callbacks - what are they? - (2006-05-30)
  [386] What is a callback? - (2005-07-22)
  [240] Conventional restraints removed - (2005-03-09)

Q110 - Object Orientation and General technical topics - Programming Algorithms
  [3620] Finding the total, average, minimum and maximum in a program - (2012-02-22)
  [3102] AND and OR operators - what is the difference between logical and bitwise varieties? - (2010-12-24)
  [3093] How many toilet rolls - hotel inventory and useage - (2010-12-18)
  [2993] Arrays v Lists - what is the difference, why use one or the other - (2010-10-10)
  [2951] Lots of way of converting 3 letter month abbreviations to numbers - (2010-09-10)
  [2894] Sorting people by their names - (2010-07-29)
  [2617] Comparing floating point numbers - a word of caution and a solution - (2010-02-01)
  [2586] And and Or illustrated by locks - (2010-01-17)
  [2509] A life lesson from the accuracy of numbers in Excel and Lua - (2009-11-21)
  [2259] Grouping rows for a summary report - MySQL and PHP - (2009-06-27)
  [2189] Matching disparate referencing systems (MediaWiki, PHP, also Tcl) - (2009-05-19)
  [1949] Nuclear Physics comes to our web site - (2008-12-17)
  [1840] Validating Credit Card Numbers - (2008-10-14)
  [1391] Ordnance Survey Grid Reference to Latitude / Longitude - (2007-10-14)
  [1187] Updating a page strictly every minute (PHP, Perl) - (2007-05-14)
  [1157] Speed Networking - a great evening and how we arranged it - (2007-04-21)
  [642] How similar are two words - (2006-03-11)
  [227] Bellringing and Programming and Objects and Perl - (2005-02-25)
  [202] Searching for numbers - (2005-02-04)


Back to
A threat in the post? Poor marketing practise from Smiletrain?
Previous and next
or
Horse's mouth home
Forward to
Which or ATOC - who reads train fares right?
Some other Articles
MySQL, MySQLi, PDO or something else - how best to talk to databases from PHP
Your PHP website - how to factor and refactor to reduce growing pains
Reading 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 Tk
Needle in a haystack - finding the web server overload
Awk v Perl
4280 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86 at 50 posts per page


This is a page archived from The Horse's Mouth at http://www.wellho.net/horse/ - the diary and writings of Graham Ellis. Every attempt was made to provide current information at the time the page was written, but things do move forward in our business - new software releases, price changes, new techniques. Please check back via our main site for current courses, prices, versions, etc - any mention of a price in "The Horse's Mouth" cannot be taken as an offer to supply at that price.

Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).

© WELL HOUSE CONSULTANTS LTD., 2014: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/mouth/3451_Why ... hash-.html • PAGE BUILT: Sun Mar 30 15:20:58 2014 • BUILD SYSTEM: WomanWithCat