Perl Programming/Variables
From Wikibooks, the open-content textbooks collection
In Perl, there are five types of variables: $calars, @rrays, %hashes, &subroutines, and *typeglobals.
Contents |
[edit] Simple variables
Variables, called scalars, are identified with the $ character, and can contain nearly any type of data. For example:
$my_variable = 3; # integers $my_variable = 3.1415926; # floating point $my_variable = 3.402823669209384634633e+38; # exponents $my_variable = $another_variable + 1; # mathematical operation $my_variable = 'Can contain text'; # strings $my_variable = \$another_variable; # scalar reference $my_variable = \@array_variable; # array reference print $my_variable;
[edit] Arrays
Arrays in Perl use the @ character to identify themselves.
@my_array = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); # numeric list @my_array = (1 .. 10); # same as above @my_array = ('John', 'Paul', 'George', 'Ringo') # strings @my_array = qw/John Paul George Ringo/ # the same - one-word strings, with less typing @my_array = qw/red blue 1 green 5/; # mixed types @my_array = (\@Array1, \@Array2, \@Array3); # array of arrays foreach my $Item (@my_array) { print "Next item is $Item \n"; }
However, when you deal with just one element of the array (using square brackets so it's not confused), then that element of the array is considered a scalar which takes the $ sigil:
$my_array[0] = 1;
As in the C programming language, the number of the first element is 0 (although as with all things in Perl, it's possible to change this if you want). Array subscripts can also use variables:
$my_array[$MyNumber] = 1;
[edit] Associative arrays
Associative arrays, or "hashes," use the % character to identify themselves.
%my_hash = ('key1' => 'value1', 'key2' => 'value2');
When using the => the left side is assumed to be quoted. For long lists, lining up keys and values aids readability.
%my_hash = ( key1 => 'value1', key2 => 'value2', key3 => 'value3', );
However, when you deal with just one element of the array (using braces), then that element of the array is considered a scalar and takes the $ identifier:
$my_hash{'key1'} = 'value1';
Associative arrays are useful when you want to refer to the items by their names.
[edit] Subroutines
Subroutines are defined by the sub function, and can be called using &, though it is not recommended. Here's an example program that calculates the Fibonnaci sequence:
sub fib { my $n = shift; return $n if $n < 2; return fib( $n - 1 ) + fib( $n - 2 ); } print fib(14);

