1. Conditional Control statements
If (conditional expression)
{
# Statement
}
Else
{
# Statement
}
Given... The when structure is as follows:
Given (scalar)
When (){}
When (){}
When (){}
When (){}
The given statement is used as follows:
#!/usr/bin/perl -wuse 5.010001;my $m=<STDIN>;given ($m){when (/[0-9]/) {print "it is a number\n";}when (/[a-z]/) {print "it is a letter\n"}default {print "\n";}}
2. Loop Control statements
(1) while (conditional expression)
{
# Loop body statement
}
(2) until (conditional expression)
{
# Loop body
}
(3) do
{
# Loop body
} While (conditional expression)
(4) foreach scalar (scalar)
{
# Loop body
}
A simple example of foreach is as follows:
#! /Usr/bin/perl-w
Foreach $ m (1 .. 10)
{
Print "$ m \ n ";
}
(5) for Loop statements are equivalent to foreach statements.
Format:
For (expression; expression)
(6) next, last, and redo of cyclic control
The next statement is used to skip this loop and execute the next loop. The last statement is used to exit the loop, and the redo statement is used to return to the beginning of this loop. The difference between next and redo is that next skips this loop. The following are examples of the three statements:
#!/usr/bin/perl -wuse 5.01;my $n;for($n=0;$n<10;$n++){say "$n";say "input a command:next,last or redo";my $com=<STDIN>;last if $com=~/last/;next if $com=~/next/;redo if $com=~/redo/;}
In the above program, the input last will jump out of the loop, the input redo will print the output of this loop again, and the input next will print the next number.
(7) The last mentioned above can only exit the current layer loop. If you want to exit the multi-layer loop, you can use a statement with a label. Example:
#!/usr/bin/perl -wuse 5.01;my $num;my $j;LABEL:for($num=0;$num<10;$num++){for($j=0;$j<$num;$j++){say "input a string";my $str=<STDIN>;if ($str=~/stop/){last LABEL;}say "you have input: $str";}}
The LABEL is added before the for loop, and the last LABEL can be used in the loop to exit the two-layer loop. In the above program, enter stop to exit the loop.
3. Define and use functions
The basic function form is
Sub <Function Name>
{
# Function body
}
For example, define a function.
Sub hello
{
Print "hello world \ n ";
}
You can use the subroutine name in the expression to add & to call it,
#! /usr/bin/perl –wsub hello{print “hello world\n”;}&hello;
Hello, world appears in the program
The following defines the guess function and uses a circular statement to guess numbers:
#!/usr/bin/perl -wmy $n=100;my $num=int(rand($n));sub guess{do {print "input a number which is in the range of (0,100)";$number=chmop(<STDIN>);if ($number == $num){print "riht\n";}elsif ($number < $num){print "too low\n";}else {print "too high\n";}}while (1);}&guess;