Link to Part 1: https://himashikarunathilake.medium.com/perl-1-5a5f4ec8c251
Link to Part 2: https://himashikarunathilake.medium.com/perl-2-12f31be96028
Link to Part 3: https://himashikarunathilake.medium.com/perl-3-daf8722151fa
Link to Part 4: https://himashikarunathilake.medium.com/perl-4-2215fa18efc3

Ниже приведен файл main.pl, который будет использоваться для запуска всех подфайлов в этом разделе:

#!/usr/bin/perl

# The fifth program in Perl.

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

say "";

say "*************** RUNNING THE MODULES.PL FILE ***************";
system("perl modules.pl");
say "__________________________________________________________________________________________";
say "";

say "*************** RUNNING THE ANONYMOUS_SUBROUTINES.PL FILE ***************";
system("perl anonymous_subroutines.pl");
say "__________________________________________________________________________________________";
say "";

say "*************** RUNNING THE FILE_HANDLING.PL FILE ***************";
system("perl file_handling.pl");
say "__________________________________________________________________________________________";
say "";

say "*************** RUNNING THE ERROR_HANDLING.PL FILE ***************";
system("perl error_handling.pl");
say "__________________________________________________________________________________________";
say "";

Модули в Perl

И модули, и пакеты в Perl представляют собой механизмы, используемые для организации кода в отдельные файлы и пространства имен, тем самым помогая создавать модульный, повторно используемый и поддерживаемый код. Модуль — это набор связанных функций, переменных и классов, тогда как пакет — это пространство имен, инкапсулирующее набор переменных и функций.

Чтобы создать модуль, необходимо создать файл с расширением «.pm» и с тем же именем, что и модуль.

Ниже приведен модуль Greet.pm:

# Create the module Greet
package Greet;

# Define a subroutine - say_hello
sub say_hello {
    my ($name) = @_;
    print "Hello, $name!\n";
}

1;

Ниже приведен скрипт Modules.pl, который будет использовать модуль Greet, созданный выше:

#!/usr/bin/perl

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

# Add the current directory to @INC
use lib '.';

# Import the Greet module
use Greet;

say "=============== Welcome to the Greet Module! ===============";

print "Please provide your name: ";
my $name = <STDIN>;
chomp $name;

say "";

# Call a function from the module
Greet::say_hello($name);

Анонимные подпрограммы

В Perl анонимная подпрограмма, также известная как «лямбда» или «замыкание», представляет собой подпрограмму без имени и полезна для создания специальных блоков кода. Его можно сохранить в скалярной переменной или передать в качестве аргумента другой подпрограмме.

#!/usr/bin/perl

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

# Create an anonymous subroutine and store it in a variable
my $add = sub {
    my ($num1, $num2) = @_;
    return $num1 + $num2;
};

say "=============== Performing Additions ===============";

print "Please provide the first number for the addition: ";
my $num1 = <STDIN>;
chomp $num1;
print "Please provide the second number for the addition: ";
my $num2 = <STDIN>;
chomp $num2;

# Call the anonymous subroutine
say "Calling the anonymous subroutine..........";
my $result = $add->($num1, $num2);
say "The addition of the two numbers is: $result";

Обработка файлов в Perl

Чтение из файла

Ниже приведен код Perl, который можно использовать для чтения информации из файла с именем input_file.txt:

#!/usr/bin/perl

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

say "=============== Reading from a File ===============";

print "Please provide the name of the input file: ";
my $inputFile = <STDIN>;
chomp $inputFile;

# Open the file in read mode
open(my $fh, '<', $inputFile) or die "ERROR! Could not open file: $!";

# Read the file line by line
while (my $line = <$fh>) {
    chomp $line;
    say $line;
}

# Close the file
close($fh);

Добавление в файл

Ниже приведен код Perl, который можно использовать для добавления информации в файл с именем input_file.txt:

#!/usr/bin/perl

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

say "=============== Reading from a File ===============";

print "Please provide the name of the input file: ";
my $inputFile = <STDIN>;
chomp $inputFile;

# Open the file in read mode
open(my $fh, '<', $inputFile) or die "ERROR! Could not open file: $!";

# Read the file line by line
while (my $line = <$fh>) {
    chomp $line;
    say $line;
}

# Close the file
close($fh);

say "";
say "";
say "";

say "=============== Appending to a File ===============";

print "Please provide the name of the input file: ";
my $appendFile = <STDIN>;
chomp $appendFile;

# Open the file in append mode
open($fh, '>>', $appendFile) or die "ERROR! Could not open file: $!";

# Append to the file
print "Please provide the text to append to the file: ";
my $text = <STDIN>;
chomp $text;
say $fh $text;

# Close the file
close($fh);

say "";
say "SUCCESS! The text has been appended to the file. Please find the modified file contents below:";
say "";
say "";

# Open the file again in read mode
open($fh, '<', $appendFile) or die "ERROR! Could not open file: $!";

# Read and print the modified file contents
while (my $line = <$fh>) {
    chomp $line;
    say $line;
}

# Close the file
close($fh);

Запись в файл

Ниже приведен код Perl, который можно использовать для записи информации в файл с именем output_file.txt:

#!/usr/bin/perl

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

say "=============== Reading from a File ===============";

print "Please provide the name of the input file: ";
my $inputFile = <STDIN>;
chomp $inputFile;

# Open the file in read mode
open(my $fh, '<', $inputFile) or die "ERROR! Could not open file: $!";

# Read the file line by line
while (my $line = <$fh>) {
    chomp $line;
    say $line;
}

# Close the file
close($fh);

say "";
say "";
say "";

say "=============== Appending to a File ===============";

print "Please provide the name of the input file: ";
my $appendFile = <STDIN>;
chomp $appendFile;

# Open the file in append mode
open($fh, '>>', $appendFile) or die "ERROR! Could not open file: $!";

# Append to the file
print "Please provide the text to append to the file: ";
my $text = <STDIN>;
chomp $text;
say $fh $text;

# Close the file
close($fh);

say "";
say "SUCCESS! The text has been appended to the file. Please find the modified file contents below:";
say "";
say "";

# Open the file again in read mode
open($fh, '<', $appendFile) or die "ERROR! Could not open file: $!";

# Read and print the modified file contents
while (my $line = <$fh>) {
    chomp $line;
    say $line;
}

# Close the file
close($fh);

say "";
say "";
say "";
say "=============== Writing to a File ===============";

print "Please provide the name of the output file: ";
my $outputFile = <STDIN>;
chomp $outputFile;

# Open the file in write mode
open($fh, '>', $outputFile) or die "ERROR! Could not open file: $!";

# Read the input from the user
print 'Please provide the text to write to the file (provide your input as a single line by using \n for line breaks): ';
$text = <STDIN>;
chomp $text;

# Replace "\n" with actual newline characters
$text =~ s/\\n/\n/g;

# Write to the file
say $fh $text;

# Close the file
close($fh);

say "";
say "SUCCESS! The text has been written to the file.";

Обработка ошибок

умереть Функция

В Perl функция die используется для завершения программы и отображения сообщения об ошибке при возникновении критической ошибки.

#!/usr/bin/perl

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

# die Function
say "To open an existing file, please provide the input file name as error_handling.txt.\nTo try out the \"die\" function, please provide the input file name as non_existent_file.txt.";
print "\nPlease provide the name of the input file: ";
my $dieInputFile= <STDIN>;
chomp $dieInputFile;

say "";

# Open the file in read mode
open(my $fh, '<', $dieInputFile) or die "ERROR! Could not open file: $!";
say "Please find the file contents below: ";
say "";

# Read the file line by line
while (my $line = <$fh>) {
    chomp $line;
    say $line;
}

функция предупреждения

Функция «warn» в Perl используется для отображения предупреждающего сообщения без завершения работы программы.

#!/usr/bin/perl

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

# die Function
say "To open an existing file, please provide the input file name as error_handling.txt.\nTo try out the \"die\" function, please provide the input file name as non_existent_file.txt.";
print "\nPlease provide the name of the input file: ";
my $dieInputFile = <STDIN>;
chomp $dieInputFile;

say "";

# Open the file in read mode
open(my $fh, '<', $dieInputFile) or die "ERROR! Could not open file: $!";
say "Please find the file contents below: ";
say "";

# Read the file line by line
while (my $line = <$fh>) {
    chomp $line;
    say $line;
}

say "";
say "";
say "";

# warn Function
say "To open an existing file, please provide the input file name as error_handling.txt.\nTo try out the \"warn\" function, please provide the input file name as too_large_file.txt.";
print "\nPlease provide the name of the input file: ";
my $warnInputFile = <STDIN>;
chomp $warnInputFile;

say "";

# Open the file in read mode
open($fh, '<', $warnInputFile) or warn "WARNING! Could not open file: $!";
say "Please find the file contents below: ";
say "";

# Read the file line by line
while (my $line = <$fh>) {
    chomp $line;
    say $line;
}

блок оценки

Блок «eval» в Perl используется для обработки исключений. Это позволяет нам перехватывать и обрабатывать исключения, предотвращая внезапное завершение программы.

#!/usr/bin/perl

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

# die Function
say "To open an existing file, please provide the input file name as error_handling.txt.\nTo try out the \"die\" function, please provide the input file name as non_existent_file.txt.";
print "\nPlease provide the name of the input file: ";
my $dieInputFile = <STDIN>;
chomp $dieInputFile;

say "";

# Open the file in read mode
open(my $fh, '<', $dieInputFile) or die "ERROR! Could not open file: $!";
say "Please find the file contents below: ";
say "";

# Read the file line by line
while (my $line = <$fh>) {
    chomp $line;
    say $line;
}

say "";
say "";
say "";

# warn Function
say "To open an existing file, please provide the input file name as error_handling.txt.\nTo try out the \"warn\" function, please provide the input file name as too_large_file.txt.";
print "\nPlease provide the name of the input file: ";
my $warnInputFile = <STDIN>;
chomp $warnInputFile;

say "";

# Open the file in read mode
open($fh, '<', $warnInputFile) or warn "WARNING! Could not open file: $!";
say "Please find the file contents below: ";
say "";

# Read the file line by line
while (my $line = <$fh>) {
    chomp $line;
    say $line;
}

say "";
say "";
say "";

# eval Block
say "To open an existing file, please provide the input file name as error_handling.txt.\nTo try out the \"eval\" block, please provide the input file name as corrupted_file.txt.";
print "\nPlease provide the name of the input file: ";
my $evalInputFile = <STDIN>;
chomp $evalInputFile;

say "";

# Open the file in read mode
eval {
    open($fh, '<', $evalInputFile) or die "ERROR! Could not open file: $!";
};
if ($@) {
    say "ERROR! Could not open file: $@";
}
say "Please find the file contents below: ";
say "";

# Read the file line by line
while (my $line = <$fh>) {
    chomp $line;
    say $line;
}

Попробуйте::Крошечный модуль

Модуль Try::Tiny в Perl можно использовать для более сложной обработки ошибок. Он обеспечивает простой и гибкий способ обработки исключений.

#!/usr/bin/perl

use strict;
use warnings;
use feature "say";
use Try::Tiny;

# die Function
say "To open an existing file, please provide the input file name as error_handling.txt.\nTo try out the \"die\" function, please provide the input file name as non_existent_file.txt.";
print "\nPlease provide the name of the input file: ";
my $dieInputFile = <STDIN>;
chomp $dieInputFile;

say "";

# Open the file in read mode
open(my $fh, '<', $dieInputFile) or die "ERROR! Could not open file: $!";
say "Please find the file contents below: ";
say "";

# Read the file line by line
while (my $line = <$fh>) {
    chomp $line;
    say $line;
}

say "";
say "";
say "";

# warn Function
say "To open an existing file, please provide the input file name as error_handling.txt.\nTo try out the \"warn\" function, please provide the input file name as too_large_file.txt.";
print "\nPlease provide the name of the input file: ";
my $warnInputFile = <STDIN>;
chomp $warnInputFile;

say "";

# Open the file in read mode
open($fh, '<', $warnInputFile) or warn "WARNING! Could not open file: $!";
say "Please find the file contents below: ";
say "";

# Read the file line by line
while (my $line = <$fh>) {
    chomp $line;
    say $line;
}

say "";
say "";
say "";

# eval Block
say "To open an existing file, please provide the input file name as error_handling.txt.\nTo try out the \"eval\" block, please provide the input file name as corrupted_file.txt.";
print "\nPlease provide the name of the input file: ";
my $evalInputFile = <STDIN>;
chomp $evalInputFile;

say "";

# Open the file in read mode
eval {
    open($fh, '<', $evalInputFile) or die "ERROR! Could not open file: $!";
};
if ($@) {
    say "ERROR! Could not open file: $@";
}
say "Please find the file contents below: ";
say "";

# Read the file line by line
while (my $line = <$fh>) {
    chomp $line;
    say $line;
}

say "";
say "";
say "";

# Try::Tiny Module
say "To open an existing file, please provide the input file name as error_handling.txt.\nTo try out the \"Try::Tiny\" module, please provide the input file name as missing_file.txt.";
print "\nPlease provide the name of the input file: ";
my $tryTinyInputFile = <STDIN>;
chomp $tryTinyInputFile;

say "";

# Open the file in read mode
try {
    open($fh, '<', $tryTinyInputFile) or die "ERROR! Could not open file: $!";
} catch {
    warn "ERROR! Could not open file: $_\n";
};
say "Please find the file contents below: ";
say "";

# Read the file line by line
while (my $line = <$fh>) {
    chomp $line;
    say $line;
}

Вы можете получить доступ к исходному коду по адресу: Perl/Perl-5 at master · Himashi-Karunathilake/Perl (github.com).

Ссылка на часть 6: «Perl — 6. В этой статье давайте рассмотрим использование нашего… | Химаши Карунатилаке | август 2023 г. | Середина"