Perl Variables

 

Overview

Perl variables store values. Strings and numbers are singular pieces of data, while lists of strings or numbers are plural. Objects look singular from the outside but plural from the inside. Singular variables are called scalars and plural variables are called arrays

Here is a hello_world.pl script using a variable:

$sed = "Howdy, world!\n";          # Set a variable.
print $sed;                        # Print the variable.

The $ character tells Perl that phrase is a scalar variable. The @ character tells Perl that a variable is an array variable.

Type Character Example Description
Scalar $ $xdollars An individual value (number or string)
Array @ @large A list of values, keyed by number
Hash % %interest A group of values, keyed by string
Subroutine & &how A callable chunk of Perl code
Typeglob * *struck Everything named struck

Double quotation marks (double quotes) do variable interpolation, Single quotes suppress interpolation. Backquotes execute an external program and return the output of the program.

$answer = 47;                     # an integer
$pi = 3.14159265;                 # a "real" number
$binum = 6.02e23;                 # scientific notation
$pet = "Puffin";                  # string
$city = "I was born in $city";    # string with interpolation
$cost = 'An ipod is $150';        # string without interpolation
$foo = $bar;                      # another variable's value
$foo = $bar * $xyz;               # an expression
$exit = system("vi $file");       # numeric status of a command
$cwd = `pwd`;                     # string output from a command

Scalars may also hold references to other data structures, including subroutines and objects.

$ary = \@myarray;            # reference to a named array
$hsh = \%myhash;             # reference to a named hash
$sub = \&mysub;              # reference to a named subroutine

$ary = [1,2,3,4,5];          # reference to an unnamed array
$hsh = {Mn => 21, Ca => 40}; # reference to an unnamed hash
$sub = sub { print $state }; # reference to an unnamed subroutine

$birdie = new Puffin "Penelope";  # reference to an object

Unassigned variables have a default value of either "" or 0, depending on context. Perl will generally convert the data into the form required by the current context, For example, suppose you said this:

$puffins = '14464';
print $puffins + 1, "\n";

The original value of $puffins is a string, but it is converted to a number to add 1 to it, and then converted back to a string to be printed out as 14465.

A reference behaves as a reference if given a "dereference" context, but otherwise acts like a simple scalar value. For example...

$birdie = new Puffin "Penelope";
if (not $birdie) 
{ 
    die "dead puffin"; 
}
$birdie->flyaway();

...creates a reference to a Puffin object and puts it into the variable $birdie, which we then test, as a scalar, to see if it is true. But on the last line, we treat $birdie as an object, asking perl to look up the flyaway() method for Puffin objects.

 

List Context Variables

Perl has two types of multivalued variables: arrays and hashes, that supply a list context to the right side of the assignment rather than a scalar context.

Use an array variable if you want to look something up by number. Use a hash variable if you want to look something up by name.

 

Arrays

An array is an ordered list of scalars, accessed by the scalar's position in the list. The list may contain numbers, strings, references to subarrays, subhashes, or a mixture of all.

To assign a list value to an array, group the values together using parentheses:

@office = ("computer", "chair", "desk", "router");

You could set four scalar variables from the array like this:

($BBC, $CBC, $NBC, $CBS) = @networks;

You can swap two variables by saying:

($alpha,$omega) = ($omega,$alpha);

To assign to one array element at a time...

$office[0] = "computer";
$office[1] = "chair";
$office[2] = "desk";
$office[3] = "router";

 

Hashes

A hash is an unordered set of scalars, associative arrays, accessed by some string value that is associated with each scalar. Unlike an array, a hash has no beginning or end.

Each pair of items in the list will be interpreted as a key/value pair, and are represented using the % symbol.

To translate abbreviated month names to the corresponding full names...

%longmonth = (
    "Jan" => "January",
    "Feb" => "February",
    "Mar" => "March",
    "Apr" => "April",
    "May" => "May",
    "Jun" => "June",
    "Jul" => "Jul",
);

Individual hash element are selected by enclosing the key in braces So Mar in the hash above would be represented using $longmonth{"Mar"}.

To construct a list as a scalar, use square brackets...

$members{"beatles"} = ["John", "Paul", "George", "Ringo"];        

To assign individual elements...

$members{"Beatles"}[0] = "John";
$members{"Beatles"}[1] = "Paul";
$members{"Beatles"}[2] = "George";
$members{"Beatles"}[3] = "Ringo";

 

Packages

To create a Puffin module...

package Puffin;

...Perl will assume from this point on that any unspecified verbs or nouns are about Puffins. It does this by automatically prefixing any global name with the module name "Puffin::". So if you say:

package Puffin;
$birdie = &fly();

...then the real name of $birdie is $Puffin::birdie. This means that if some other module says:

package Bird;
$birdie = &fly();
Perl won't get confused, because the real name of this $birdie is $Bird::birdie, not $Puffin::birdie. A package establishes a namespace. You can have as many namespaces as you like, but since you're only in one of them at a time, you can pretend that the other namespaces don't exist.

Packages classify verbs so that other packages can use them. When we said...

$birdie = new Puffin "Penelope";

...we were actually invoking the &new verb in the Puffin package, which has the full name of &Puffin::new. And when we said:

$birdie->flyaway();

...we were invoking the &Puffin::flyaway routine, because $birdie remembers that it is pointing to a Puffin. This is how object-oriented programming works.

To use an existing Puffin package...

use Puffin;
$birdie = new Puffin "Penelope";

The Comprehensive Perl Archive Network (CPAN) contains numerous existing packages that you can plug into your application.

 

Pragmas

The pragma modules change the way Perl behavies. For example...

use strict;

...forces one to be more explicit about various things that Perl would otherwise guess about, such as how you want your variables to be scoped.