Tinkering with Perl

Jonathan's Corner (Search & Sitemap) > A Library of Free Online Books to Read > Miscellaneous Nonfiction > Tinkering with Perl
Skip Back  Previous  26  27  28  29  30  31  32  33  34  35  Next  Skip Forward
Printer-Friendly Version

Assignment of hashes

Hashes may be assigned one of two ways: one of which remembles a scalar, and the other of which is like the assignment of a list.

Recall the earlier example where John, Sue, and Mary have a dog, a cat, and a goldfish respectively. The easiest way, and the one you should probably use most of the time (until you've outgrown this book), is to say, "John's pet is a dog. Sue's pet is a cat. Mary's pet is a goldfish." In Perl, we write it this way:

$Pet{"John"} = "dog";
$Pet{"Sue"} = "cat";
$Pet{"Mary"} = "goldfish";

Remember that $Pet{"John"} should be read as "John's pet." This means that the whole statement should be read, "Let John's pet be a dog." Even though the computer statement looks rather funny, it really says something that is fairly close to English.

The second way makes a bunch of assignments at once — it is useful when you want to create a hash from scratch. Creating the same hash this way would look like this:

%Pet = ("John" => "dog",
	"Sue"  => "cat",
	"Mary" => "goldfish");

Now, did you notice that the statement was broken over a few lines? It's OK to split a statement over several lines and put spaces in to format it; indeed, it is good to do so. It makes the code more readable. This is called spacing.

See also:

Variables in general - Hashes - Statements - Assignment of variables in general - Assignment of scalars - Assignment of lists - Functions

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) > A Library of Free Online Books to Read > Miscellaneous Nonfiction > Tinkering with Perl
Skip Back  Previous  26  27  28  29  30  31  32  33  34  35  Next  Skip Forward
Printer-Friendly Version