Perl — 2

Himashi Karunathilake
17 min readAug 14, 2023

--

Image from https://www.vectorlogo.zone/logos/perl/perl-ar21.svg
Link to Part 1: https://medium.com/@himashikarunathilake/perl-1-5a5f4ec8c251

Given below is the main.pl file that will be used to run all the sub files in this section:

#!/usr/bin/perl

# The second program in Perl.

use strict;
use warnings;
use feature "say";

say "";

say "*************** RUNNING THE ARRAYS.PL FILE ***************";
system("perl arrays.pl");
say "__________________________________________________________________________________________";
say "";

say "*************** RUNNING THE HASHES.PL FILE ***************";
system("perl hashes.pl");
say "__________________________________________________________________________________________";
say "";

say "*************** RUNNING THE OPERATORS.PL FILE ***************";
system("perl operators.pl");
say "__________________________________________________________________________________________";
say "";

say "*************** RUNNING THE FORMAT_SPECIFIERS.PL FILE ***************";
system("perl format_specifiers.pl");
say "__________________________________________________________________________________________";
say "";

say "*************** RUNNING THE STRING_MANIPULATION.PL FILE ***************";
system("perl string_manipulation.pl");
say "__________________________________________________________________________________________";
say "";

Perl Arrays

Arrays in Perl are ordered collections of scalar values that can hold a single value like numbers or strings. They can be used for tasks like storing data sets, collections of values, etc.

Declaring an Array

In Perl, arrays are denoted by the “@” prefix.

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# Declare an array
my @names = ("Dwight", "Jim", "Pam");

Accessing Elements in an Array

To access a particular element n in an array in Perl, you should provide the (n-1) as the index value. This is because, indexing starts from 0 (i.e., the first element in an array will have an index of (1–1) → 0, second element will have an index of (2–1) → 1, etc.).

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# Declare an array
my @names = ("Dwight", "Jim", "Pam");

# Print the second element - "Jim"
say "The second element of the array: ", $names[1];
Accessing a particular element in Perl

Printing an Array

To print a complete array, simply provide the name of the array without an index. When printing a complete array, in order to get a more readable output with comma separated elements, we can use the join() function to concatenate the elements using a comma and a space delimiter.

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# Declare an array
my @names = ("Dwight", "Jim", "Pam");

# Print the second element - "Jim"
say "The second element of the array: ", $names[1];

say "";

# Print the complete array with a delimiter (comma and space)
say "The complete array: ", join(", ", @names);
Printing the complete array

Adding Elements to an Array

To add elements to the end of an array in Perl, we can use the push function.

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# Declare an array
my @names = ("Dwight", "Jim", "Pam");

# Print the second element - "Jim"
say "The second element of the array: ", $names[1];

say "";

# Print the complete array with a delimiter (comma and space)
say "The complete array: ", join(", ", @names);

say "";

# Add an element to the end of the array
push @names, "Michael";
say "The updated array after adding an element to the end: ", join(", ", @names);
Adding elements to the end of an array

To add elements to the beginning of an array, we can use the unshift function.

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# Declare an array
my @names = ("Dwight", "Jim", "Pam");

# Print the second element - "Jim"
say "The second element of the array: ", $names[1];

say "";

# Print the complete array with a delimiter (comma and space)
say "The complete array: ", join(", ", @names);

say "";

# Add an element to the end of the array
push @names, "Michael";
say "The updated array after adding an element to the end: ", join(", ", @names);

say "";

# Add an element to the beginning of the array
unshift @names, "Ryan";
say "The updated array after adding an element to the beginning: ", join(", ", @names);
Adding elements to the beginning of an array

Removing Elements from an Array

To remove elements from the end of an array, we can use the pop function.

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# Declare an array
my @names = ("Dwight", "Jim", "Pam");

# Print the second element - "Jim"
say "The second element of the array: ", $names[1];

say "";

# Print the complete array with a delimiter (comma and space)
say "The complete array: ", join(", ", @names);

say "";

# Add an element to the end of the array
push @names, "Michael";
say "The updated array after adding an element to the end: ", join(", ", @names);

say "";

# Add an element to the beginning of the array
unshift @names, "Ryan";
say "The updated array after adding an element to the beginning: ", join(", ", @names);

say "";

# Remove an element from the end of the array
pop @names;
say "The updated array after removing an element from the end: ", join(", ", @names);
Removing an element from the end of an array

To remove an element from the beginning of an array, we can use the shift function.

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# Declare an array
my @names = ("Dwight", "Jim", "Pam");

# Print the second element - "Jim"
say "The second element of the array: ", $names[1];

say "";

# Print the complete array with a delimiter (comma and space)
say "The complete array: ", join(", ", @names);

say "";

# Add an element to the end of the array
push @names, "Michael";
say "The updated array after adding an element to the end: ", join(", ", @names);

say "";

# Add an element to the beginning of the array
unshift @names, "Ryan";
say "The updated array after adding an element to the beginning: ", join(", ", @names);

say "";

# Remove an element from the end of the array
pop @names;
say "The updated array after removing an element from the end: ", join(", ", @names);

say "";

# Remove an element from the beginning of the array
shift @names;
say "The updated array after removing an element from the beginning: ", join(", ", @names);
Removing an element from the beginning of an array

Size of an Array

To obtain the size of an array or the number of elements in an array, we can use the scalar function.

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# Declare an array
my @names = ("Dwight", "Jim", "Pam");

# Print the second element - "Jim"
say "The second element of the array: ", $names[1];

say "";

# Print the complete array with a delimiter (comma and space)
say "The complete array: ", join(", ", @names);

say "";

# Add an element to the end of the array
push @names, "Michael";
say "The updated array after adding an element to the end: ", join(", ", @names);

say "";

# Add an element to the beginning of the array
unshift @names, "Ryan";
say "The updated array after adding an element to the beginning: ", join(", ", @names);

say "";

# Remove an element from the end of the array
pop @names;
say "The updated array after removing an element from the end: ", join(", ", @names);

say "";

# Remove an element from the beginning of the array
shift @names;
say "The updated array after removing an element from the beginning: ", join(", ", @names);

say "";

# Obtain the size of the array
my $size = scalar @names;
say "The size of the array (no. of elements): ", $size;
Obtaining the size of an array

Hashes in Perl

In Perl, a hash is a collection of key-value pairs and is also known as an associative array. Hashes allow us to store and retrieve data based on a unique key rather than numerical indices, making them more flexible for data organization and retrieval.

Creating a Hash

To create a hash, we have to use the “%” symbol before the name of the hash. Hash keys and values are separated by a fat comma (=>).

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# Creating a hash
my %marks = (
"Dwight" => 95,
"Jim" => 75,
"Pam" => 85
);

Accessing Elements in a Hash

You can access hash values using the keys.

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# Creating a hash
my %marks = (
"Dwight" => 95,
"Jim" => 75,
"Pam" => 85
);

# Accessing the value of a key - "Dwight"
say "The value of the key \"Dwight\": ", $marks{"Dwight"};

Printing a Hash

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# Creating a hash
my %marks = (
"Dwight" => 95,
"Jim" => 75,
"Pam" => 85
);

# Accessing the value of a key - "Dwight"
say "The value of the key \"Dwight\": ", $marks{"Dwight"};

say "";

# Accessing a complete hash
say "The complete hash: ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}
Printing a complete hash

Adding an Element to the Hash

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# Creating a hash
my %marks = (
"Dwight" => 95,
"Jim" => 75,
"Pam" => 85
);

# Accessing the value of a key - "Dwight"
say "The value of the key \"Dwight\": ", $marks{"Dwight"};

say "";

# Accessing a complete hash
say "The complete hash: ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}

say "";

# Adding a new key-value pair
$marks{"Michael"} = 65;
say "The updated hash after adding a new key-value pair: ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}
Adding a key-value pair to the hash

Modifying Elements in a Hash

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# Creating a hash
my %marks = (
"Dwight" => 95,
"Jim" => 75,
"Pam" => 85
);

# Accessing the value of a key - "Dwight"
say "The value of the key \"Dwight\": ", $marks{"Dwight"};

say "";

# Accessing a complete hash
say "The complete hash: ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}

say "";

# Adding a new key-value pair
$marks{"Michael"} = 65;
say "The updated hash after adding a new key-value pair: ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}

say "";

# Modifying the value of an existing key
$marks{"Jim"} = 80;
say "The updated hash after modifying the value of an existing key - \"Jim\": ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}
Modifying the value of an existing key-value pair

Removing an Element from a Hash

We can delete a key-value pair from a hash using the delete function.

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# Creating a hash
my %marks = (
"Dwight" => 95,
"Jim" => 75,
"Pam" => 85
);

# Accessing the value of a key - "Dwight"
say "The value of the key \"Dwight\": ", $marks{"Dwight"};

say "";

# Accessing a complete hash
say "The complete hash: ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}

say "";

# Adding a new key-value pair
$marks{"Michael"} = 65;
say "The updated hash after adding a new key-value pair: ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}

say "";

# Modifying the value of an existing key
$marks{"Jim"} = 80;
say "The updated hash after modifying the value of an existing key - \"Jim\": ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}

say "";

# Removing a key-value pair
delete $marks{"Michael"};
say "The updated hash after removing a key-value pair - \"Michael\": ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}
Removing a key-value pair

Check if a Key Exists in a Hash

We can use the exists function to check if a specific key exists in a given hash.

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# Creating a hash
my %marks = (
"Dwight" => 95,
"Jim" => 75,
"Pam" => 85
);

# Accessing the value of a key - "Dwight"
say "The value of the key \"Dwight\": ", $marks{"Dwight"};

say "";

# Accessing a complete hash
say "The complete hash: ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}

say "";

# Adding a new key-value pair
$marks{"Michael"} = 65;
say "The updated hash after adding a new key-value pair: ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}

say "";

# Modifying the value of an existing key
$marks{"Jim"} = 80;
say "The updated hash after modifying the value of an existing key - \"Jim\": ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}

say "";

# Removing a key-value pair
delete $marks{"Michael"};
say "The updated hash after removing a key-value pair - \"Michael\": ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}

say "";

# Check if a key exists in the hash
if (exists $marks{"Pam"}) {
say "The key \"Pam\" exists in the hash.";
} else {
say "The key \"Pam\" does not exist in the hash.";
}
Checking if a key exists in a hash

Hash Slices

Hash slices allow you to retrieve multiple values at once using an array of keys.

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# Creating a hash
my %marks = (
"Dwight" => 95,
"Jim" => 75,
"Pam" => 85
);

# Accessing the value of a key - "Dwight"
say "The value of the key \"Dwight\": ", $marks{"Dwight"};

say "";

# Accessing a complete hash
say "The complete hash: ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}

say "";

# Adding a new key-value pair
$marks{"Michael"} = 65;
say "The updated hash after adding a new key-value pair: ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}

say "";

# Modifying the value of an existing key
$marks{"Jim"} = 80;
say "The updated hash after modifying the value of an existing key - \"Jim\": ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}

say "";

# Removing a key-value pair
delete $marks{"Michael"};
say "The updated hash after removing a key-value pair - \"Michael\": ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}

say "";

# Check if a key exists in the hash
if (exists $marks{"Pam"}) {
say "The key \"Pam\" exists in the hash.";
} else {
say "The key \"Pam\" does not exist in the hash.";
}

say "";

# Hash slices
my @keys = ("Dwight", "Jim");
my @values = @marks{@keys};
say "The hash slice for the keys \"Dwight\" and \"Jim\": ", join(", ", @values);
A hash slice

Nested Hashes

Nested hashes in Perl are a way to create complex data structures where a hash contains another hash as its value, allowing us to organize and represent data in a hierarchical manner, similar to multi-dimensional arrays.

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# Creating a hash
my %marks = (
"Dwight" => 95,
"Jim" => 75,
"Pam" => 85
);

# Accessing the value of a key - "Dwight"
say "The value of the key \"Dwight\": ", $marks{"Dwight"};

say "";

# Accessing a complete hash
say "The complete hash: ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}

say "";

# Adding a new key-value pair
$marks{"Michael"} = 65;
say "The updated hash after adding a new key-value pair: ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}

say "";

# Modifying the value of an existing key
$marks{"Jim"} = 80;
say "The updated hash after modifying the value of an existing key - \"Jim\": ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}

say "";

# Removing a key-value pair
delete $marks{"Michael"};
say "The updated hash after removing a key-value pair - \"Michael\": ";
foreach my $key (keys %marks) {
say "\t$key: $marks{$key}";
}

say "";

# Check if a key exists in the hash
if (exists $marks{"Pam"}) {
say "The key \"Pam\" exists in the hash.";
} else {
say "The key \"Pam\" does not exist in the hash.";
}

say "";

# Hash slices
my @keys = ("Dwight", "Jim");
my @values = @marks{@keys};
say "The hash slice for the keys \"Dwight\" and \"Jim\": ", join(", ", @values);

say "";

# Nested hashes
my %report = (
"Dwight" => {
"Maths" => 95,
"English" => 85
},
"Jim" => {
"Maths" => 75,
"English" => 65
},
"Pam" => {
"Maths" => 85,
"English" => 95
}
);

# Accessing a value in a nested hash - "Dwights's Maths Marks"
say "Dwight's Maths Marks: ", $report{"Dwight"}{"Maths"};

say "";

# Accessing a complete nested hash
say "The complete nested hash: ";
foreach my $key (keys %report) {
say "\t$key: ";
foreach my $subkey (keys %{$report{$key}}) {
say "\t\t$subkey: $report{$key}{$subkey}";
}
}
Output when working with a nested hash

Operators in Perl

Arithmetic Operators

Arithmetic operations in Perl can be performed by utilizing the following arithmetic operators.

Addition          +
Subtraction -
Multiplication *
Division /
Remainder %
#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# Arithmetic operators
my $var1 = 5;
my $var2 = 2;

say "var1 = $var1\tvar2 = $var2";
say "Addition of the two variables: ", ($var1 + $var2);
say "Subtraction of the two variables: ", ($var1 - $var2);
say "Multiplication of the two variables: ", ($var1 * $var2);
say "Division of var1 by var2: ", ($var1 / $var2);
say "Remainder when var1 is divided by var2: ", ($var1 % $var2);
say "var1 to the power of var2: ", ($var1 ** $var2);
Arithmetic operations in Perl

String Formatting

Given below is a list of some format specifiers available in Perl.

%s        Formats the value as a string
%d or %i Formats the value as a decimal integer
%f Formats the value as a floating-point number
%e Formats the value as a scientific notation (exponential format)
%c Formats the value as a character
%b Formats the value as a binary representation
%x or %X Formats the value as a hexadecimal representation
%o Formats the value as an octal respresentation
%s or %d Formats the value as an array or a hash
%% Formats the value as a percentage
#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

my $name = "Dwight";
my $age = 30;
my $height = 1.82;

# Printf formats according to format specifiers
printf("Name: %s\nAge: %d\nHeight: %.2f\n", $name, $age, $height);
Format specifiers

String Manipulation

In Perl, the “.” operator can be used for string concatenation to join two or more strings together.

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# String concatenation
say "===== String Concatenation =====";
my $first_name = "Dwight";
my $last_name = "Schrute";
my $full_name = $first_name . " " . $last_name;
say "Full Name: $full_name";
String concatenation

In Perl, strings can be defined in both single quotes (‘’) or double quotes (“”) based on what we want to accomplish. Strings enclosed in double quotes are interpolated, meaning that the variable names are replaced by their original values, and strings enclosed within single quotes are not interpolated (no replacements occur).

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# String concatenation
say "===== String Concatenation =====";
my $first_name = "Dwight";
my $last_name = "Schrute";
my $full_name = $first_name . " " . $last_name;
say "Full Name: $full_name";

say "";

# String interpolation
say "===== String Interpolation =====";
my $var = "The Office";
say "var = \"The Office\"";
say "This is an interpolated string where the string is encapsulated in double quotes. Welcome to $var!";
say 'This is a non-interpolated string where the string is encapsulated in single quotes. Welcome to $var!';
String interpolation

Strings can be repeated for a desired number of times using the “x” operator after defining the string.

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# String concatenation
say "===== String Concatenation =====";
my $first_name = "Dwight";
my $last_name = "Schrute";
my $full_name = $first_name . " " . $last_name;
say "Full Name: $full_name";

say "";

# String interpolation
say "===== String Interpolation =====";
my $var = "The Office";
say "var = \"The Office\"";
say "This is an interpolated string where the string is encapsulated in double quotes. Welcome to $var!";
say 'This is a non-interpolated string where the string is encapsulated in single quotes. Welcome to $var!';

say "";

# String repetition
say "===== String Repetition =====";
my $repeatString = "Hello " x 5;
say "$repeatString";
String repetition

The length of a given string can be found using the length() function.

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# String concatenation
say "===== String Concatenation =====";
my $first_name = "Dwight";
my $last_name = "Schrute";
my $full_name = $first_name . " " . $last_name;
say "Full Name: $full_name";

say "";

# String interpolation
say "===== String Interpolation =====";
my $var = "The Office";
say "var = \"The Office\"";
say "This is an interpolated string where the string is encapsulated in double quotes. Welcome to $var!";
say 'This is a non-interpolated string where the string is encapsulated in single quotes. Welcome to $var!';

say "";

# String repetition
say "===== String Repetition =====";
my $repeatString = "Hello " x 5;
say "$repeatString";

say "";

# String length
say "===== String Length =====";
my $string = "Hello World!";
say "Length of the string \"$string\": ", length($string);
String length

We can also use an existing string to extract and define a substring using the substr() function.

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# String concatenation
say "===== String Concatenation =====";
my $first_name = "Dwight";
my $last_name = "Schrute";
my $full_name = $first_name . " " . $last_name;
say "Full Name: $full_name";

say "";

# String interpolation
say "===== String Interpolation =====";
my $var = "The Office";
say "var = \"The Office\"";
say "This is an interpolated string where the string is encapsulated in double quotes. Welcome to $var!";
say 'This is a non-interpolated string where the string is encapsulated in single quotes. Welcome to $var!';

say "";

# String repetition
say "===== String Repetition =====";
my $repeatString = "Hello " x 5;
say "$repeatString";

say "";

# String length
say "===== String Length =====";
my $string = "Hello World!";
say "Length of the string \"$string\": ", length($string);

say "";

# Substrings
say "===== Substrings =====";
my $substring = substr($string, 0, 5);
say "Substring of \"$string\" from index 0 to 5: $substring";
Substrings

We can also replace a part of a string, using the “s///” substitution operator.

s/text_to_be_replaced/new_replacement_text/
#!/usr/bin/perl

use strict;
use warnings;
use feature "say";

# String concatenation
say "===== String Concatenation =====";
my $first_name = "Dwight";
my $last_name = "Schrute";
my $full_name = $first_name . " " . $last_name;
say "Full Name: $full_name";

say "";

# String interpolation
say "===== String Interpolation =====";
my $var = "The Office";
say "var = \"The Office\"";
say "This is an interpolated string where the string is encapsulated in double quotes. Welcome to $var!";
say 'This is a non-interpolated string where the string is encapsulated in single quotes. Welcome to $var!';

say "";

# String repetition
say "===== String Repetition =====";
my $repeatString = "Hello " x 5;
say "$repeatString";

say "";

# String length
say "===== String Length =====";
my $string = "Hello World!";
say "Length of the string \"$string\": ", length($string);

say "";

# Substrings
say "===== Substrings =====";
my $substring = substr($string, 0, 5);
say "Substring of \"$string\" from index 0 to 5: $substring";

say "";

# String replacement
say "===== String Replacement =====";
say "String before replacement: $string";
my $stringReplace = $string;
$stringReplace =~ s/World/Perl/;
say "String after replacement: $stringReplace";
String replacement

--

--

Himashi Karunathilake

I am a cybersecurity enthusiast and writer with a passion for demystifying complex topics. Join me as I explore the ever-evolving world of cybersecurity!