SUSE Linux 10.0 Unleashed

Variables in Perl come in three types: scalar, arrays, and hashes.

  • Scalar variables are those that hold a single value. Scalars are preceded by a $ sign in the code. Some assignment statement examples using scalar variables are

    $x = 5; $pi = 3.14159; $animal = "dog";

  • Arrays are numerically indexed lists of scalar data. Arrays are identified in Perl by the @ sign. An example of an array is

    @months = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

  • Hashes are collections of scalar values arranged in key/value pairs. Hashes are identified with a % sign. An example of a hash is

    %birthdays = ("mom" => "SEP 06", "jean" => "JUN 01", "marc" => "JUN 16");

Scalars can be strings or numbers and can change from one type to the other, depending on the operator. If an operator expects a number, Perl will see the value as a number, and if an operator expects a string, Perl will see a string. This lets you concentrate less on the difference between numbers and strings, as long as you get the operator right (you'll learn about operators in the next section).

Arrays follow the same syntactical conventions as scalars. Each scalar value that makes up an array can be referred to as $<array>[index#], where, in this case, # is a numerical index. The index begins at 0, meaning that the first item in the list is 0, the second is 1, and so on.

Hashes were originally called associative arrays. The => identifier is called a fat comma because it behaves much like a comma in other contexts. In fact, commas could be used to define the preceding hash, but the fat commas make it more legible. Compare:

%birthdays = ("mom", "SEP 06", "jean", "JUN 01", "marc", "JUN 16");

Категории