Skip to content

Perl Variables

Variables are named storage locations in memory. In Perl, the type of data a variable can hold is indicated by its ‘sigil’ - a special character at the beginning of its name.

Modern Perl programming strongly advocates for use strict; and use warnings;. With use strict;, variables must be declared before use, typically with my, which gives them lexical scope (limited to the enclosing block, file, or eval).

Perl has three main built-in data types, each with a corresponding variable type:

  • Scalars ($): Hold a single value, like a number, a string, or a reference.
  • Arrays (@): Hold an ordered list of scalars.
  • Hashes (%): Hold an unordered collection of key-value pairs (associative arrays).

Perl maintains separate namespaces for different variable types. This means $name, @name, and %name are distinct variables.

With use strict; in effect, you must declare variables using my (for lexical scope), our (for package variables, lexically scoped), or state (for persistent lexical variables, Perl 5.10+). The most common is my.

The equals sign (=) is used for assignment.

my $age = 30; # Scalar: integer assignment
my $name = "Jane Doe"; # Scalar: string assignment
my $pi = 3.14159; # Scalar: floating-point number
my @colors = ("red", "green", "blue"); # Array of strings
my %capitals = ( # Hash: key => value pairs
"USA" => "Washington D.C.",
"France" => "Paris",
);

A scalar variable holds a single piece of data. This can be a number (integer or floating-point), a string, or a reference (which points to another data structure).

#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
my $count = 10;
my $message = "Processing complete.";
my $temperature = 25.5;
say "Count: $count";
say "Message: $message";
say "Temperature: $temperature C";

Output:

Count: 10
Message: Processing complete.
Temperature: 25.5 C

An array variable stores an ordered list of scalar values. Array indices start at 0.

To access a single element of an array, use the $ sigil with the array name, followed by the index in square brackets (e.g., $array_name[0]).

#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
my @fruits = ("apple", "banana", "cherry");
say "First fruit: $fruits[0]"; # Accessing the first element
say "Second fruit: $fruits[1]";
$fruits[2] = "mango"; # Modifying an element
say "All fruits: @fruits"; # Interpolates the array with spaces
my $num_fruits = @fruits; # In scalar context, an array returns its size
say "Number of fruits: $num_fruits";

Output:

First fruit: apple
Second fruit: banana
All fruits: apple banana mango
Number of fruits: 3

Common array operations include push (add to end), pop (remove from end), shift (remove from start), and unshift (add to start).

A hash variable stores a collection of key-value pairs. Keys are unique strings, and values are scalars. Hashes are unordered (though recent Perl versions offer some ordering consistency for iteration, it shouldn’t be relied upon for programmatic logic).

To access a single element of a hash, use the $ sigil with the hash name, followed by the key in curly braces (e.g., $hash_name{key}). The ‘fat comma’ (=>) is often used for readability when defining hashes.

#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
my %ages = (
"Alice" => 30,
"Bob" => 24,
"Carol" => 42,
);
say "Alice's age: $ages{Alice}";
$ages{David} = 19; # Adding a new key-value pair
# Iterating through a hash
say "Known ages:";
foreach my $name (keys %ages) { # 'keys %ages' returns a list of all keys
say " $name is $ages{$name} years old.";
}

Output (order of iteration may vary):

Alice's age: 30
Known ages:
Carol is 42 years old.
David is 19 years old.
Alice is 30 years old.
Bob is 24 years old.

Perl determines how to interpret a variable or expression based on the ‘context’ in which it’s used. The two primary contexts are scalar context and list context.

#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
my @elements = ('A', 'B', 'C');
# List context: assigning to an array copies elements
my @copy_of_elements = @elements;
say "Copy: @copy_of_elements"; # Output: Copy: A B C
# Scalar context: assigning to a scalar gives the number of elements
my $count_of_elements = @elements;
say "Count: $count_of_elements"; # Output: Count: 3
# String context (a type of scalar context)
my $string_representation = "@elements";
say "String: $string_representation"; # Output: String: A B C (elements joined by space)

Understanding context is crucial for writing correct Perl code. Other contexts include boolean (true/false evaluation) and void (value discarded).

For further learning, explore references, which allow creating complex data structures like arrays of hashes or hashes of arrays. Also, explore Perl’s object-oriented features for larger applications.