SoFunction
Updated on 2025-04-07

perl control structure conditional control if while

1. Conditional judgment
  if ( <expression>) {
    <statement_block_1>
  }
  elsif ( <expression> ) {
    <statement_block_2>
  }
  ...
  else{
    <statement_block_3>
  }
2. Circulation:
1. While loop
  while ( <expression> ) {
    <statement_block>
  }
2. Until loop
  until ( <expression> ) {
    <statement_block>
  }
3. For loop of C, such as
  for ($count=1; $count <= 5; $count++) {
    # statements inside the loop go here
  }
Here 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, the syntax is:
  foreach localvar (listexpr) {
    statement_block;
  }
example:
  foreach $word (@words) {
    if ($word eq "the") {
      print ("found the word 'the'\n"); 
    }
  }
Note:
(1) The loop variable localvar here is a local variable. If it already has a value before this, the value will still be restored after the loop.
(2) Change local variables in a loop, and the corresponding array variables will also change, such as:
  @list = (1, 2, 3, 4, 5);
  foreach $temp (@list) {
    if ($temp == 2) {
      $temp = 20;
    }
  }
At this time @list has become (1, 20, 3, 4, 5).
5. Do loop
  do {
    statement_block
  } while_or_until (condexpr);
The do loop executes at least once.
6. Cycle control
Exiting the loop is last, which has the same effect as break in C; executing the next loop is next, which has the same effect as continue in C; a command unique to PERL is redo, which means repeating this loop, that is, the loop variable remains unchanged and returns to the start point of the loop, but be noted that the redo command does not work in the do loop.
7. Traditional goto label; statement.

3. 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 later, it is executed first.