Tinkering with Perl

Jonathan's Corner (Search & Sitemap) > Writing > Miscellaneous Nonfiction > Tinkering with Perl
Skip Back  Previous  20  21  22  23  24  25  26  27  28  29  Next  Skip Forward
Printer-Friendly Version

Hashes

Hashes are a little more complicated than either lists or scalars, but they are very useful.

Let's say that you know some people, and you want to keep track of what kind of pets they have. Suppose that you know John, Sue, and Mary. Let's also suppose that John has a dog, Sue has a cat, and Mary has a goldfish. What would be good would be a single variable, called Pet: if you plugged in John, you would get dog; if you plugged in Sue, you would get cat; if you plugged in Mary, you would get goldfish.

A hash is a variable that can do that. We refer to a hash in slightly different ways, depending on what you want to do. If you refer to the whole hash, you put a percent sign ('%') in front of the hash. So the hash with the pets might be:

%pet

But if you want to refer to a specific pet -- say, you want to find out what pet Mary has -- you would do it like this:

$pet{"Mary"}
(We put the "Mary" in quotes, because it is a href="../../definitions/string.html">string, and the computer will get confused if it sees the letters M, a, r, and y all by themselves.)

The expression

$pet{"Mary"}

should be read as, "Mary's pet".

See also:

Variables in general - Scalars - Lists - Assignment of variables - Assignment of hashes

Tinkering with Perl is a free book that provides an introduction to programming in Perl, as well as a basic reference for things like foreach in Perl, if-then, and if-then-else, in addition to providing a glossary where you can find definitions for concatenate and other terms.

Tinkering with Perl may be one of the most popular offerings on this site, but it's not the only attraction. You can read a tongue-in-cheek Game Review: Meatspace, read an even more offbeat customer service survey (whether or not you actually fill it out), and spend a few minutes wishing your boss would read, The Administrator Who Cried, "Important!" (Not to mention that there are other things you can read here besides tech stuff, from Janra Ball: The Headache to The Spectacles.)

Read more...

Top

Jonathan's Corner (Search & Sitemap) > Writing > Miscellaneous Nonfiction > Tinkering with Perl
Skip Back  Previous  20  21  22  23  24  25  26  27  28  29  Next  Skip Forward
Printer-Friendly Version