Web Developer's Virtual Library: Encyclopedia of Web Design Tutorials, Articles and Discussions


WDVL Newsletter

Active Server Pages
JSP/Java Servlets
Microsoft SQL Server
Daily Backup
Dedicated Servers
Streaming Audio/Video
24-hour Support    

jobs.webdeveloper.com

Hiermenus


e-commerce
Partner With Us















Developer Channel
FlashKit.com
JavaScript.com
JavaScriptSource
Developer Jobs
ScriptSearch
StreamingMediaWorld
Web Developer's Journal
Web Developer's Virtual Library
WebDeveloper.com
Webreference
Web Hosts
XMLfiles.com

internet.com
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers


Perl Variables: Hashes

April 26, 1999

The third and last type of traditional variable that we'll look at in Perl is the hash. Hashes are conceptually similar to lists in some respects, but offer a different and highly useful extra functionality.

Recall our shopping list -- in its original form, this data was suited to a Perl list because it was merely an arbitrary list of items. But would this list be useful in the real world? If Susan were to hand her husband Melvin this list, he might pick up milk, but which milk would he buy? Perhaps Susan would want Melvin to purchase the brand of milk on sale this week, meaning that the specific brand to buy may change from week to week. In this case, the grocery list must be expanded so that it can relate the items to some additional information; e.g.

"milk" is related with "Holy Cow Brand 1%"
"eggs" is related with "Store Brand Large"
"bread" is related with "Smurf Bakery Light Wheat"

The above data, in Perl parlance, is known as a set of key-value pairs. On the left side are the keys ("milk","eggs", and "bread") and on the right side are the values. A hash, then, is actually a list of key-value pairs. Hashes are referred to with the prefix %. Creating the initial hash for this grocery list is simple:

%shopping=("milk","Holy Cow 1%",
           "eggs","Store Brand Large",
           "bread","Smurf Bakery Light Wheat");

As with lists, any single item in the hash is referred to as a scalar variable. Unlike lists -- and this is where the power of hashes come in -- the order of the items is unimportant. Hashes do not use indexes to see their data, they use the keys. So, if we wanted to see the value for the key "milk":

print $shopping{"milk"};

The above line would output "Holy Cow 1%". Next week, when the sales change, Susan can easily assign a different milk brand value to the milk key:

$shopping{"milk"}="Heffer 2000 Skim";

You can add new key-value pairs to the hash at any time using a simple assignment:

$shopping{"dessert"}="HunkaHunka Premium Ice Cream";

Hashes are incredibly useful when you want to create a list but you also want to look up data from the list using related bits of data, rather than meaningless index numbers. Admittedly, most of the people in charge of the weekly grocery list don't manage it using Perl hashes -- but two quite practical examples quickly spring to mind:

  1. A translation table. Imagine that you are looking up data from a database, and you have used field names to look up the data. So, the field "RINV" might represent the "Remaining Inventory" field. When you output this data to the screen you might want to reproduce the field labels, but "RINV" is rather cryptic. It would be easy to setup a hash that translates the database field names into human-readable field names:
    %fields("RINV","Remaining
    Inventory","TINV","Total Inventory");
    print "$fields{'RINV'}: $ValueFromDatabase\n";
    
  2. Frequency analysis. You are a celebrity linguist designing a word-frequency analyzer to help determine how often your own name appears in newspaper articles. Each unique word counted is entered as the key of a hash; the number of instances of this word is updated as the value of the hash. First, initialize an empty hash table:
    %freq=();

    Imagine that $word represents the most recent word read in from the source data:

    $freq{$word}++;

    The above line increments the value of the specified key. Requesting the frequency of the word "happy" then becomes trivially easy:

    $freq{"happy"}

Perl Variables: Lists (aka Arrays)
The Perl You Need to Know
Perl Functions


Up to => Home / Authoring / Languages / Perl / PerlfortheWeb




Jupiter Online Media: internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and Jupiter Online Media

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Web Hosting | Newsletters | Tech Jobs | Shopping | E-mail Offers