Книга: Fedora™ Unleashed, 2008 edition

Perl Variable Types

Perl Variable Types

There are three variable types in Perl: scalars, arrays, and hashes. A different character is used to signify each variable type.

Scalar variables are indicated with the $ character, as in $penguin. Scalars can be numbers or strings, and they can change type from one to the other as needed. If you treat a number like a string, it becomes a string. If you treat a string like a number, it is translated into a number if it makes sense to do so; otherwise, it usually evaluates to 0. For example, the string "76trombones" evaluates as the number 76 if used in a numerical calculation, but the string "polar bear" will evaluate to 0.

Perl arrays are indicated with the @ character, as in @fish. An array is a list of values that are referenced by index number, starting with the first element numbered 0, just as in C and awk. Each element in the array is a scalar value. Because scalar values are indicated with the $ character, a single element in an array is also indicated with a $ character.

For example, $fish[2] refers to the third element in the @fish array. This tends to throw some people off, but is similar to arrays in C in which the first array element is 0.

Hashes are indicated with the % character, as in %employee. A hash is a list of name and value pairs. Individual elements in the hash are referenced by name rather than by index (unlike an array). Again, because the values are scalars, the $ character is used for individual elements.

For example, $employee{name} gives you one value from the hash. Two rather useful functions for dealing with hashes are keys and values. The keys function returns an array containing all the keys of the hash, and values returns an array of the values of the hash. Using this approach, the Perl program in Listing 25.2 displays all the values in your environment, much like typing the bash shell's env command.

LISTING 25.2 Displaying the Contents of the env Hash

#!/usr/bin/perl
foreach $key (keys %ENV) {
 print "$key = $ENV{$key}n";
}

Оглавление книги

Оглавление статьи/книги

Генерация: 1.060. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз