Link to Part 1: https://himashikarunathilake.medium.com/perl-1-5a5f4ec8c251 Link to Part 2: https://himashikarunathilake.medium.com/perl-2-12f31be96028
Ниже приведен файл main.pl, который будет использоваться для запуска всех подфайлов в этом разделе:
#!/usr/bin/perl # The third program in Perl. use strict; use warnings; use feature "say"; say ""; say "*************** RUNNING THE INPUT_STATEMENT.PL FILE ***************"; system("perl input_statement.pl"); say "__________________________________________________________________________________________"; say ""; say "*************** RUNNING THE CONDITIONS.PL FILE ***************"; system("perl conditions.pl"); say "__________________________________________________________________________________________"; say ""; say "*************** RUNNING THE LOOPS.PL FILE ***************"; system("perl loops.pl"); say "__________________________________________________________________________________________"; say ""; say "*************** RUNNING THE SPECIAL_STATEMENTS.PL FILE ***************"; system("perl special_statements.pl"); say "__________________________________________________________________________________________"; say "";
Входной оператор
Чтобы прочитать вводимые пользователем данные или файл в Perl, мы можем использовать оператор ромба «‹><», поскольку он считывает вводимые данные построчно.
#!/usr/bin/perl use strict; use warnings; use feature "say"; print "Enter your first name: "; # Read the input from the user and assign it to a variable my $first_name = <STDIN>; # Remove the newline character from the input chomp $first_name; say "Hi $first_name!";
#!/usr/bin/perl use strict; use warnings; use feature "say"; print "Enter your first name: "; # Read the input from the user and assign it to a variable my $first_name = <STDIN>; # Remove the newline character from the input chomp $first_name; say "Hi $first_name!"; say ""; # Obtain the name of the file to be read print "Enter the name of the file to be read (with the file extension): "; my $file_name = <STDIN>; chomp $file_name; # Read input from the file open my $file, '<', $file_name or die "Error! Cannot open file: $!"; my $i = 1; while (<$file>) { chomp; print "Line $i of file: $_\n"; $i++; } close $file;
Заявления об условиях
если заявление
Следующий фрагмент кода проверяет, указывает ли пользователь фамилию. Если на входе указано значение -1, программа выйдет из этого конкретного блока кода.
#!/usr/bin/perl use strict; use warnings; use feature "say"; # if statement print "Enter your last name (-1 to exit): "; my $last_name = <STDIN>; chomp $last_name; if ($last_name ne "-1") { say "$last_name\'s Conditions Program"; }
Оператор if-else
Следующий фрагмент кода проверяет, является ли пользователь совершеннолетним на основе введенных данных.
#!/usr/bin/perl use strict; use warnings; use feature "say"; # if statement print "Enter your last name (-1 to exit): "; my $last_name = <STDIN>; chomp $last_name; if ($last_name ne "-1") { say "$last_name\'s Conditions Program"; } say ""; # if-else statement print "Enter your age: "; my $age = <STDIN>; chomp $age; if ($age >= 18) { say "You are an adult!"; } else { say "You are a child!"; }
If required,you can also follow the following format to have multiple conditions within an if-else statement: if (condition1) { # Statements to be executed if the condition1 is met } elsif (condition2) { # Statements to be executed if the condition2 is met } elsif (condition3) { # Statements to be executed if the condition3 is met } ... ... ... } else { # Statements to be executed if none of the above conditions are met }
Условные операторы с тернарным оператором
Тернарный оператор позволяет писать компактные условные операторы.
condition ? expression_if_true : expression_if_false; #!/usr/bin/perl use strict; use warnings; use feature "say"; # if statement print "Enter your last name (-1 to exit): "; my $last_name = <STDIN>; chomp $last_name; if ($last_name ne "-1") { say "$last_name\'s Conditions Program"; } say ""; # if-else statement print "Enter your age: "; my $age = <STDIN>; chomp $age; if ($age >= 18) { say "You are an adult!"; } else { say "You are a child!"; } say ""; # Terenary operator print "Enter the current temperature: "; my $temperature = <STDIN>; chomp $temperature; my $weather = ($temperature > 25) ? "warm" : "cold"; say "The current weather is $weather!";
если заявление
Как обсуждалось выше, оператор if будет выполнен, если данное условие выполнено. Однако мы можем использовать оператор if, который будет выполняться, если данное условие не выполнено.
#!/usr/bin/perl use strict; use warnings; use feature "say"; # if statement print "Enter your last name (-1 to exit): "; my $last_name = <STDIN>; chomp $last_name; if ($last_name ne "-1") { say "$last_name\'s Conditions Program"; } say ""; # if-else statement print "Enter your age: "; my $age = <STDIN>; chomp $age; if ($age >= 18) { say "You are an adult!"; } else { say "You are a child!"; } say ""; # Terenary operator print "Enter the current temperature: "; my $temperature = <STDIN>; chomp $temperature; my $weather = ($temperature > 25) ? "warm" : "cold"; say "The current weather is $weather!"; say ""; # unless statement print "Enter your city (-1 to exit): "; my $city = <STDIN>; chomp $city; unless ($city eq "-1") { say "$city is the most beautiful city in the world!"; }
The unless statement can be also modified as an unless-else statement as follows: unless (condition) { # Statements to be executed if the condition is not met } else { # Statements to be executed if the condition is not met } It can be further modified into a unless-elsif-else statement as follows: unless (condition1) { # Statements to be executed if the condition1 is not met } elsif (condition2) { # Statements to be executed if the condition2 is met } elsif (condition3) { # Statements to be executed if the condition3 is met } ... ... ... } else { # Statements to be executed if none of the above conditions are met }
Петли
для цикла
Повторно выполняет блок кода до тех пор, пока не будет выполнено заданное условие.
#!/usr/bin/perl use strict; use warnings; use feature "say"; # for loop say "Printing numbers less than 5.........."; for (my $i = 0; $i < 5; $i++) { print "$i\t"; } say "";
пока цикл
Цикл while в Perl многократно выполняет блок кода до тех пор, пока заданное условие истинно.
#!/usr/bin/perl use strict; use warnings; use feature "say"; # for loop say "Printing numbers less than 5.........."; for (my $i = 0; $i < 5; $i++) { print "$i\t"; } say ""; say ""; say ""; # while loop print "Please enter a number less than or equal to 10: "; my $number = <STDIN>; chomp $number; if ($number <= 10) { say "Printing numbers less than $number.........."; my $j = 0; while ($j < $number) { print "$j\t"; $j++; } } else { say "ERROR! The number $number is greater than 10.\n"; } say "";
до цикла
Цикл Until в Perl аналогичен циклу while, но продолжает выполняться до тех пор, пока заданное условие ложно.
#!/usr/bin/perl use strict; use warnings; use feature "say"; # for loop say "Printing numbers less than 5.........."; for (my $i = 0; $i < 5; $i++) { print "$i\t"; } say ""; say ""; say ""; # while loop print "Please enter a number less than or equal to 10: "; my $number = <STDIN>; chomp $number; if ($number <= 10) { say "Printing numbers less than $number.........."; my $j = 0; while ($j < $number) { print "$j\t"; $j++; } } else { say "ERROR! The number $number is greater than 10.\n"; } say ""; say ""; say ""; # until loop say "Printing numbers from 1 to 10 in the descending order.........."; my $k = 10; until ($k == 0) { print "$k\t"; $k--; } say "";
цикл foreach
Цикл foreach используется для перебора элементов массива или списка.
#!/usr/bin/perl use strict; use warnings; use feature "say"; # for loop say "Printing numbers less than 5.........."; for (my $i = 0; $i < 5; $i++) { print "$i\t"; } say ""; say ""; say ""; # while loop print "Please enter a number less than or equal to 10: "; my $number = <STDIN>; chomp $number; if ($number <= 10) { say "Printing numbers less than $number.........."; my $j = 0; while ($j < $number) { print "$j\t"; $j++; } } else { say "ERROR! The number $number is greater than 10.\n"; } say ""; say ""; say ""; # until loop say "Printing numbers from 1 to 10 in the descending order.........."; my $k = 10; until ($k == 0) { print "$k\t"; $k--; } say ""; say ""; say ""; # foreach loop my @names = ("Dwight", "Jim", "Pam", "Michael", "Oscar", "Angela", "Kevin", "Andy", "Ryan", "Toby"); say "Printing the names.........."; foreach my $name (@names) { print "$name\t"; } say "";
цикл «делай пока»
Цикл do- while аналогичен циклу while, но в этом случае цикл do- while выполняется хотя бы один раз, поскольку условие проверяется только после первого выполнения.
#!/usr/bin/perl use strict; use warnings; use feature "say"; # for loop say "Printing numbers less than 5.........."; for (my $i = 0; $i < 5; $i++) { print "$i\t"; } say ""; say ""; say ""; # while loop print "Please enter a number less than or equal to 10: "; my $number = <STDIN>; chomp $number; if ($number <= 10) { say "Printing numbers less than $number.........."; my $j = 0; while ($j < $number) { print "$j\t"; $j++; } } else { say "ERROR! The number $number is greater than 10.\n"; } say ""; say ""; say ""; # until loop say "Printing numbers from 1 to 10 in the descending order.........."; my $k = 10; until ($k == 0) { print "$k\t"; $k--; } say ""; say ""; say ""; # foreach loop my @names = ("Dwight", "Jim", "Pam", "Michael", "Oscar", "Angela", "Kevin", "Andy", "Ryan", "Toby"); say "Printing the names.........."; foreach my $name (@names) { print "$name\t"; } say ""; say ""; say ""; # do-while loop say "Printing numbers from 1 to 10 in the ascending order.........."; my $l = 1; do { print "$l\t"; $l++; } while ($l <= 10); say "";
Специальные заявления
последнее заявление
Чтобы получить эквивалент оператора «break», мы можем использовать оператор «last» для завершения самого внутреннего цикла.
#!/usr/bin/perl use strict; use warnings; use feature "say"; # last statement say "Printing numbers till 13 is met.........."; for (my $i = 0; $i < 20; $i++) { if ($i == 13) { last; } print "$i\t"; } say "";
следующее заявление
Чтобы получить эквивалент оператора «continue», мы можем использовать оператор «next», чтобы пропустить оставшиеся итерации текущей итерации цикла и перейти к следующей. итерация.
#!/usr/bin/perl use strict; use warnings; use feature "say"; # last statement say "Printing numbers till 13 is met.........."; for (my $i = 0; $i < 20; $i++) { if ($i == 13) { last; } print "$i\t"; } say ""; say ""; say ""; # next statement say "Printing odd numbers less than 20.........."; for (my $j = 0; $j < 20; $j++) { if ($j % 2 == 0) { next; } print "$j\t"; } say "";
заявление о возврате
Оператор return в Perl используется для прекращения выполнения подпрограммы (функции) и возврата значения, если оно ожидается.
#!/usr/bin/perl use strict; use warnings; use feature "say"; sub add { my ($num1, $num2) = @_; return $num1 + $num2; } # last statement say "Printing numbers till 13 is met.........."; for (my $i = 0; $i < 20; $i++) { if ($i == 13) { last; } print "$i\t"; } say ""; say ""; say ""; # next statement say "Printing odd numbers less than 20.........."; for (my $j = 0; $j < 20; $j++) { if ($j % 2 == 0) { next; } print "$j\t"; } say ""; say ""; say ""; # return statement say "Proceeding to add two numbers.........."; print "Enter the first number: "; my $num1 = <STDIN>; chomp $num1; print "Enter the second number: "; my $num2 = <STDIN>; chomp $num2; my $sum = add($num1, $num2); say "The sum of the two numbers are: $sum";
Вы можете получить доступ к исходному коду по адресу: Perl/Part-3 at master · Himashi-Karunathilake/Perl (github.com).
Ссылка на часть 4: «Perl — 4. Ниже приведен файл main.pl, который… | Химаши Карунатилаке | август 2023 г. | Середина"