Link to Part 1: https://medium.com/@himashikarunathilake/perl-1-5a5f4ec8c251

По-долу е даден файлът main.pl, който ще се използва за изпълнение на всички подфайлове в този раздел:

#!/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 масиви

Масивите в Perl са подредени колекции от скаларни стойности, които могат да съдържат една стойност като числа или низове. Те могат да се използват за задачи като съхраняване на набори от данни, колекции от стойности и др.

Деклариране на масив

В Perl масивите се обозначават с префикса “@”.

#!/usr/bin/perl

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

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

Достъп до елементи в масив

За достъп до определен елемент n в масив в Perl, трябва да предоставите (n-1) като стойността на индекса. Това е така, защото индексирането започва от 0 (т.е. първият елемент в масива ще има индекс (1–1) → 0, вторият елемент ще има индекс (2–1) → 1 и т.н.).

#!/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];

Отпечатване на масив

За да отпечатате пълен масив, просто въведете името на масива без индекс. Когато отпечатваме пълен масив, за да получим по-четлив изход с елементи, разделени със запетая, можем да използваме функциятаjoin() за свързване на елементите с помощта на запетая и разделител за интервал.

#!/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);

Добавяне на елементи към масив

За да добавим елементи към края на масив в Perl, можем да използваме функцията push.

#!/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);

За да добавим елементи към началото на масив, можем да използваме функцията unshift.

#!/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);

Премахване на елементи от масив

За да премахнем елементи от края на масив, можем да използваме функцията pop.

#!/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);

За да премахнем елемент от началото на масив, можем да използваме функцията shift.

#!/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);

Размер на масив

За да получим размера на масива или броя на елементите в масива, можем да използваме функцията скаларна.

#!/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;

Хешове в Perl

В Perl хешът е колекция от двойки ключ-стойност и е известен също като асоциативен масив. Хешовете ни позволяват да съхраняваме и извличаме данни въз основа на уникален ключ, а не на числови индекси, което ги прави по-гъвкави за организиране и извличане на данни.

Създаване на хеш

За да създадем хеш, трябва да използваме символа “%” преди името на хеша. Хеш ключовете и стойностите са разделени с дебела запетая (=›).

#!/usr/bin/perl

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

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

Достъп до елементи в хеш

Можете да получите достъп до хеш стойности с помощта на ключовете.

#!/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"};

Отпечатване на хеш

#!/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}";
}

Добавяне на елемент към хеша

#!/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}";
}

Модифициране на елементи в хеш

#!/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}";
}

Премахване на елемент от хеш

Можем да изтрием двойка ключ-стойност от хеш с помощта на функцията delete.

#!/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}";
}

Проверете дали съществува ключ в хеш

Можем да използваме функцията exists, за да проверим дали конкретен ключ съществува в даден хеш.

#!/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.";
}

Хеш срезове

Хеш срезовете ви позволяват да извличате множество стойности наведнъж, като използвате масив от ключове.

#!/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);

Вложени хешове

Вложените хешове в Perl са начин за създаване на сложни структури от данни, където хешът съдържа друг хеш като своя стойност, което ни позволява да организираме и представяме данните по йерархичен начин, подобно на многоизмерните масиви.

#!/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}";
    }
}

Оператори в Perl

Аритметични оператори

Аритметичните операции в Perl могат да се извършват чрез използване на следните аритметични оператори.

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);

Форматиране на низове

По-долу е даден списък на някои спецификатори на формати, налични в 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);

Манипулиране на низове

В Perl операторът “.” може да се използва за конкатенация на низове за свързване на два или повече низа заедно.

#!/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";

В Perl низовете могат да бъдат дефинирани както в единични кавички (‘’), така и в двойни кавички (“”) въз основа на това, което искаме да постигнем. Низовете, затворени в двойни кавички, се интерполират, което означава, че имената на променливите се заменят с оригиналните им стойности, а низовете, затворени в единични кавички, не се интерполират (няма замени).

#!/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!';

Низовете могат да се повтарят желан брой пъти с помощта на оператора “x” след дефиниране на низа.

#!/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";

Дължината на даден низ може да бъде намерена с помощта на функцията length().

#!/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);

Можем също да използваме съществуващ низ, за ​​да извлечем и дефинираме подниз с помощта на функцията substr().

#!/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";

Можем също да заменим част от низ, като използваме оператора за заместване “s///”.

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";

Можете да получите достъп до изходния код на адрес: Perl/Part-2 at master · Himashi-Karunathilake/Perl (github.com).

Връзка към част 3: Perl — 3. По-долу е даден файлът main.pl, който… | от Himashi Karunathilake | август 2023 | Среден