Beginning CGI Programming with Perl

Learning Perl

Exercise 1.1. Working with Perl variables

In this Perl exercise, you will learn how to use variable names in your Perl program. Variable names in programs are like different types of storage containers. My wife just got back from the container store with hundreds, thousands, millions of different types of boxes, racks, and containers to straighten out all our stuff. It was just too much for my feeble programming mind, and I ran screaming from the house. Well, not really, but she did buy lots of different styles of containers for storing our STUFF. Some programming languages are like that-they have lots of different storage containers, called variables, for storing your programming data. Sometimes that’s helpful, but sometimes it’s confusing. Perl takes the simple approach: it gives you three basic containers to store your data in-kind of like having only a shoe box, water can, and a file box to store all your household STUFF. This frustrates some and pleases others. For most of your programming tasks, you’ll find Perl’s three containers simple, understandable, and completely adequate.

Imagine for a moment that you were trying to use your shoe box, water can, and file box for storing STUFF. You could put your shoes into your watering can, and water your plants using your file box, and lots of people use shoe boxes to store their important papers, but it’s usually a better idea to use storage containers for their intended purpose.


One of the confusing yet powerful features of Perl is its capability to distinguish between variable names based on the beginning character of the variable. All variables in Perl begin with a dollar sign ($), at sign (@), or percent sign (%). You also can use the ampersand (&) to begin subroutine calls. The asterisk (*) is a wildcard and refers to any variable. Definitions for these variables follow:

  • The dollar sign ($) refers to strings or numbers. Perl figures out whether it is a string or number for you most of the time. In fact, you can use the same variable as both a string and a number in different contexts. If I try to add two numbers together, Perl is smart enough to add them like numbers. If I try to use the same number at a later place in my code as character or string data, Perl treats the variable like a string. Pretty cool, huh?!
  • The at sign (@) refers to arrays indexed by numbers. These are the traditional programming language arrays.
  • The percent sign (%) refers to arrays indexed by strings. Perl refers to these as associative arrays. They are used extensively by many Perl programs, and special built-in functions, such as the key function, help you manage associative arrays. I use the key function in an example in Tutorial 6 and give a full explanation of it then.

Leave a Reply

Your email address will not be published. Required fields are marked *