Perl Variables — Declaring and Using Variables in Perl

Declaring Variables in Perl

The most important thing to say about variables in Perl, before we get into any further details, is that you should always write use strict and use warnings at the top of your program, then declare all variables with my.

use strict ensures that all variables must be declared with my (or local) before you use them, helping to eliminate typos.

use warnings ensures that your script will warn you about uninitialized variables. Always using strict and warnings will save you a huge amount of time in the long run.

Let's take a look at how you declare each of the three main data types in Perl. We'll initialize each type to a zero, blank or 'empty' value; in Perl you don't have to initialize variables, but most of the time it makes for clearer and more trouble-free code if you do so.

# Mandatory variable declaration.
use strict; 

# Warn about uninitialized variables.
use warnings; 

# Using a main() subroutine helps to make
# your script easier to read.
sub main
    my $greeting = "hello";
    print $greeting;

# Call main.


Variable Prefixes in Perl

Although Perl is not strongly typed, you need to prefix your variables with a symbol that indicates what kind of data it refers to. There are only three commonly-used basic types; scalars, arrays and hashes (also known as associative arrays).

  • scalars ($ prefix) contain single values -- which can be strings, numbers or even references to other data types or functions.

  • arrays (@ prefix) contain lists of scalar values.

  • hashes (% prefix) contain key/value pairs; the keys and values are scalars.

# A scalar initialized to an empty string.
my $some_text = '';
# A scalar initialized to zero.
my $some_number = 0;
# An empty array.
my @an_array = ();
# An empty hash.
my %a_hash = ();

Initializing Variables in Perl

Let's look at how we can initialize variables in Perl with more useful data.

# A string.
my $some_text = 'Hello there.';

# A number
my $some_number = 123;

# An array of strings.
my @an_array = ('apple', 'orange', 'banana');

# An array of numbers.
my @another_array = (0, 6.2, 9, 10);

# A hash of week day indexes vs. names.
# We can use either strings or numbers as
# both hash keys and values in Perl.
# Note the comma at the end of every initalization
# line. There is no need to miss off the last comma.

my %a_hash = (
    0 => 'Sunday',
    1 => 'Monday',
    2 => 'Tuesday',
    3 => 'Wednesday',
    4 => 'Thursday',
    5 => 'Friday',
    6 => 'Saturday',