Learning Perl - Variables


Learning Perl - Variables


I will attempt to explain things in this post in a way that is easy to understand, even for those who are new to programming.

Firstly we need to understand what variables actually are.

Variables are fundamental components in programming that allow you to store data temporarily while your program runs.

A variable can be anything from a simple number to a complex data structure. They are named storage locations in your program that can hold different values at different times.

In Perl, variables can hold different types of data, such as numbers, strings, or more complex structures like references to arrays and hashes. Understanding how to use variables effectively is crucial for writing efficient and readable Perl programs.

Variables are at the heart of every Perl program. They allow you to store, manipulate, and retrieve data as your program runs. Perl makes working with variables simple and flexible, giving you the power to handle everything from single values to complex data structures with ease.

Perl uses three main types of variables, each identified by a special symbol (sigil):

  • Scalars ('$') : Store a single value.
  • Arrays ('@') : Store ordered lists of values.
  • Hashes ('%') : Store unordered sets of key-value pairs.

There are several ways of defining a variable in perl using different keywords based upon the scope that you would like your variable declared. We will go into scope in more detail later but here is a reference table of keywords that can be used to declare variables:

Keyword Scope Description
my Lexical Local to the block, file, or eval in which it is declared.
our Global Visible throughout the package, can be used to share variables across files.
state Lexical Maintains its value between calls to the block, useful for persistent state.

Okay so I like to learn by example, let's create our very first Perl script that uses variables.

First, ensure you have Perl installed on your system. You can check this by running perl -v in your terminal. If Perl is installed, you should see the version information.

Next, create a new file called 'variables.pl' and open it in your favourite text editor. Add the following code to the file:

#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
# Declare a scalar variable
my $message = "Hello World";
say $message;
Enter fullscreen mode Exit fullscreen mode

Now save your file and run it in the terminal with the command:

perl variables.pl
Enter fullscreen mode Exit fullscreen mode

You should see the output:

Hello World
Enter fullscreen mode Exit fullscreen mode

You do not need to declare the variable to print(say) text, we do this simply for demonstration purposes but as you can see we have defined a new scalar variable that contains the string "Hello World" we then use the variable in the say statement which in-turn prints the text to the terminal.

lets now learn how to modify the variable. Add the following lines to the end of 'variables.pl':

$message = "Hello Perl";
say $message;
Enter fullscreen mode Exit fullscreen mode

This will print:

Hello Perl
Enter fullscreen mode Exit fullscreen mode

As you can see, we simply reassign a new value to the '$message' variable the same way we instantiate the variable minus the 'my' keyword as the variable is already defined, in perl you can reassign pretty much any variable during runtime unless it is locked or readonly.

Next lets create an array variable. Modify your variables.pl file to include the following code:

# Declare an array variable
my @fruits = ('apple', 'banana', 'cherry');
say "Fruits: @fruits";
# Accessing individual elements
say "First fruit: $fruits[0]";
Enter fullscreen mode Exit fullscreen mode

Now save your file and run it again. You should see this additional output:

Fruits: apple banana cherry
First fruit: apple
Enter fullscreen mode Exit fullscreen mode

In this example, we declared an array variable @fruits that contains three elements: 'apple', 'banana', and 'cherry'. We then printed the entire array and accessed the first element using $fruits[0]. Note that when accessing an array element, we use $ before the variable name, as it retrieves a scalar value from the array. I will go into more details on manipulating an array in the next post.

For this tutorial, let's next create a hash variable. Modify your 'variables.pl' file to include the following code:

# Declare a hash variable
my %person = (
    name => 'Lisa',
    age  => 33,
    city => 'Pluto'
);
say "Name: $person{name}";
say "Age: $person{age}";
say "City: $person{city}";
Enter fullscreen mode Exit fullscreen mode

Now save your file and run it again. You should see this additional output:

Name: Lisa
Age: 33
City: Pluto
Enter fullscreen mode Exit fullscreen mode

In this example, we declared a hash variable '%person' that contains three key-value pairs: 'name', 'age', and 'city'. We then accessed each value using the corresponding key. Note when accessing a hash value we use $ and not %, as we are retrieving a scalar value from the hash. Again I will go into more details on manipulating a hash in a later post.

An array and a hash can also be something we call references in perl, which allows us to create more complex data structures. When accessing references, we use the '->' operator. Add the following code to the end of your 'variables.pl' file:

# Declare a reference to an array
my $array_ref = \@fruits;
say "Array reference: @{$array_ref}";
say "Second fruit: $array_ref->[1]";
# Declare a reference to a hash
my $hash_ref = \%person;
say "Hash reference: $hash_ref->{name}, $hash_ref->{age}, $hash_ref->{city}";
Enter fullscreen mode Exit fullscreen mode

Now save your file and run it again. You should see this additional output:

Array reference: apple banana cherry
Second fruit: banana
Hash reference: Lisa, 33, Pluto
Enter fullscreen mode Exit fullscreen mode

In this example, we created a reference to the '@fruits' array and the '%person' hash. We accessed the array reference using '@{$array_ref}' and the hash reference using '$hash_ref->{key}'.

What is important to understand is that scalars are very flexible and can hold almost any kind of data, making them a powerful tool in Perl programming.

In this post, we have covered the basics of variables in Perl, in the next post we will explore arrays more in depth, including how to manipulate them, add and remove elements, and iterate through them. Until then I hope you found this post useful and informative. If you have any questions or need further clarification on anything, feel free to ask in the comments below. Happy coding!

Related Blogs

Learning Perl – Introduction
Perl has long been known as the “duct tape of the Internet,” or "the Swiss Army chainsaw of scripting...
Learning Perl - Arrays
As stated in the previous post, Perl has three types of variables: scalars, arrays and hashes. Today...
Learning Perl - Hashes
In the last post we covered the basics of arrays, today we will look at hashes in more detail. What...
Learning Perl - Conditional Statements
So far we have covered basic variables in Perl, today we are going to look at how to use these...
Learning Perl - Loops and Iteration
In previous posts, we explored variables, arrays, hashes, and conditional statements in Perl. Now...
Learning Perl - Scalars
Before moving onto more complex topics lets come back to how we represent data in Perl. The most...
Learning Perl - References
In the last post we learnt how to create a reference to a scalar, an array, and a hash. In this post,...
Learning Perl - Ternary Operators
In a previous post, we learned about conditional statements in Perl. The ternary operator is an...
Learning Perl - Subroutines
Subroutines are one of the most important building blocks in programming. They allow you to organise...
Learning Perl - Regular Expressions
Regular expressions also known as regex or regexp, are a powerful way to match patterns in text. Most...
Learning Perl - Modules
A module in Perl is a reusable piece of code that can be included in your scripts to provide...
Learning Perl - CPAN
In the last post I showed you how to create a new module and how to use it in your code. In this post...
Learning Perl - Plain Old Documentation
When you write and program in any language it is good practice to document your code. Each language...
Learning Perl - Testing
In this post we will look at how to test Perl code using the Test::More module. Like documentation,...
Learning Perl - Exporting
In programming, we often want to share functionality across different parts of our code. In Perl,...
Learning Perl - Object Orientation
Object-Oriented Programming (OOP) is a widely used programming paradigm that enables the creation of...
Learning Perl - Inheritance
In the last post we discussed Object Oriented Programming in Perl, focusing on the basics of creating...
Learning Perl - File Handles
In programming file processing is a key skill to master. Files are essential for storing data,...
Learning Perl - Prototypes
Today we are going to discuss Perl subroutine prototypes, which are a way to enforce a certain...
Learning Perl - Overloading Operators
In the last post we investigated prototype subroutines in Perl. In this post, we will look at...