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;
Now save your file and run it in the terminal with the command:
perl variables.pl
You should see the output:
Hello World
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;
This will print:
Hello Perl
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]";
Now save your file and run it again. You should see this additional output:
Fruits: apple banana cherry
First fruit: apple
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}";
Now save your file and run it again. You should see this additional output:
Name: Lisa
Age: 33
City: Pluto
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}";
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
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!
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.