Seventh chapter control Structure
by Flamephoenix
First, condition judgment
Second, the cycle:
1. While loop
2. Until cycle
3. For loop
4. Foreach loop for each element of the list (array)
5. Do Loop
6. Cyclic control
7, the traditional goto statement
Three, single-line conditions
First, condition judgment
if (<expression>) {
<statement_block_1>
}
elsif (<expression>) {
<statement_block_2>
}
...
else{
<statement_block_3>
}
Second, the cycle:
1. While loop
while (<expression>) {
<statement_block>
}
2. Until cycle
Until (<expression>) {
<statement_block>
}
3, Class C for loops, such as
for ($count =1; $count <= 5; $count + +) {
# statements inside the loop go here
}
The following is an example of using the comma operator in A for loop:
for ($line = <stdin>, $count = 1; $count <= 3; $line = <stdin>, $count + +) {
Print ($line);
}
It is equivalent to the following statement:
$line = <STDIN>;
$count = 1;
while ($count <= 3) {
Print ($line);
$line = <STDIN>;
$count + +;
}
4. Loop for each element of the list (array): foreach, Syntax:
foreach Localvar (listexpr) {
Statement_block;
}
Cases:
foreach $word (@words) {
if ($word eq "the") {
Print ("found the word ' \ n");
}
}
Note:
(1) The loop variable Localvar here is a local variable, and if it already has a value before that, the value will still be restored after the loop.
(2) Change the local variable in the loop, the corresponding array variable will also change, such as:
@list = (1, 2, 3, 4, 5);
foreach $temp (@list) {
if ($temp = = 2) {
$temp = 20;
}
}
At this point the @list has become (1, 20, 3, 4, 5).
5. Do Loop
do {
Statement_block
} while_or_until (condexpr);
The Do loop executes at least one loop.
6. Cyclic control
Exit loop is last, same as break in C, execution of Next loop is next, same as continue in C; a Perl-specific command is redo, which means repeating the loop, that is, the loop variable is the same, and back to the starting point of the loop, but be aware that The redo command does not work in the Do loop.
7. The traditional goto label;
Three, single-line conditions
The syntax is statement keyword CONDEXPR. Where keyword can be if, unless, while, or until, such as:
Print ("This is zero.\n") if ($var = = 0);
Print ("This is zero.\n") unless ($var! = 0);
Print ("Not zero yet.\n") while ($var--> 0);
Print ("Not Zero yet.\n") until ($var--= = 0);
Although the conditional judgment is written in the back, it is executed first.
Previous chapter Next Chapter catalogue
PERL5 Seventh Chapter control structure