8.4 Dollar, Percent and At

So, when do we use $, % and @?

It helps to equate these symbols to English words. The dollar symbol, $, is like the word ``that''. It is singular. In Perl, the $ symbol represents a ``scalar'' value. For now, let us just say that $ means atomic and singularity, not a collection of something.

There are two built-in collection types in Perl. The simpler one is the ``list'' type, and other one is the ``hash'' type. A list of items is nothing more than a sequence of items, in which the order is significant. A hash of items is like a phone book of items so that each item has a ``name'' (key) to uniquely identify itself from all the other items.

The % symbol is similar to the phrase ``that phone book of ...'' In other words, %ENV is ``that phone book of environment variables''. The @ symbol is similar to the phrase ``that list of ...'' So, @envkeys is ``that list of names of environment variables''.

Now, how come $ENV{$key} is right, and %ENV{$key} is incorrect?

Let's use our informal English translation. %ENV{$key} is roughly ``the value of that phone book of environment variables with the name same as the value of $key.'' This makes no sense! There is at most one single definition in the phone book with the name identical to the value of $key.

$ENV{$key}, on the other hand, means ``the value of that environment variable with the name identical to the value of $key.'' This makes a lot more sense.

Note that in Perl, a variable must be preceded by one of $, % or @.

Copyright © 2008-05-09 by Tak Auyeung