Main Content

Perl - a list or a hash?

Archive - Originally posted on "The Horse's Mouth" - 2006-12-06 18:02:28 - Graham Ellis

You can hold multiple scalars in either a list or a hash in Perl. A list (signaled by an @ character or [..] around the subscript) is ordered - i.e. the elements are numbered and the order is significant. In contrast, a hash (signalled by a % character or {..} around the subscript) is unordered; the elements are named and the order isn't easily predicted.

Why would anyone want to use a hash if it's not in order? Well - if you want to look things up based on a key it's very easy and very efficient. And if you've keyed data and use lists, it's quite awkward to write the code to keep them in step. Here's an example:

# Using a list - works but bulky

@onco = ("Nathan","Steve","Andrew");
@from = ("London","Romford","Cardiff");

print "Where is ... from ? ";
chop ($name = <STDIN>);

for ($k=0; $k<@onco; $k++) {
  if ($onco[$k] eq $name) {
    print "$name is from $from[$k]\n";
  }
}

# Using a hash - an unordered collection

%pep_tab = ("Nathan" => "Brighton",
  "Steve" => "Walthamstow",
  "Andrew" => "London");

print "Where is ... from ? ";
chop ($name = <STDIN>);

print "$name was from $pep_tab{$name}\n";


It turns out that hashes have many, many other uses too - their very quick look up algorithm is great for anything from checking for a word in a dictionary through to analysing all the client computers registed in your web access log.