第七章 控製結構

【 條件判斷 】
  if ( <expression>) {
    <statement_block_1>
  }
  elsif ( <expression> ) {
    <statement_block_2>
  }
  ...
  else{
    <statement_block_3>
  }
【 循環 】
1、while循環
  while ( <expression> ) {
    <statement_block>
  }
2、until循環
  until ( <expression> ) {
    <statement_block>
  }
3、類C的for循環,如
  for ($count=1; $count <= 5; $count++) {
    # statements inside the loop go here
  }
下面是在for循環中使用逗號操作符的例子︰
  for ($line = <STDIN>, $count = 1; $count <= 3;   $line = <STDIN>, $count++) {
    print ($line);
  }
它等價於下列語句︰
  $line = <STDIN>;
  $count = 1;
  while ($count <= 3) {
    print ($line);
    $line = <STDIN>;
    $count++;
  }
4、針對列表(數組)每個元素的循環︰foreach,語法為︰
  foreach localvar (listexpr) {
    statement_block;
  }
例︰
  foreach $word (@words) {
    if ($word eq "the") {
      print ("found the word 'the'\n");
    }
  }
注︰
(1)此處的循環變量localvar是個局部變量,如果在此之前它已有值,則循環後仍恢複該值。
(2)在循環中改變局部變量,相應的數組變量也會改變,如︰
  @list = (1, 2, 3, 4, 5);
  foreach $temp (@list) {
    if ($temp == 2) {
      $temp = 20;
    }
  }
此時@list已變成了(1, 20, 3, 4, 5)。
5、do循環
  do {
    statement_block
  } while_or_until (condexpr);
  do循環至少執行一次循環。
6、循環控製
  退出循環為last,與C中的break作用相同;執行下一個循環為next,與C中的continue作用相同;PERL特有的一個命令是redo,其含義是重複此次循環,即循環變量不變,回到循環起始點,但要注意,redo命令在do循環中不起作用。
7、傳統的goto label;語句。
【 單行條件 】
  語法為statement keyword condexpr。其中keyword可為if、unless、while或until,如︰
    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);
  雖然條件判斷寫在後面,但卻是先執行的。

CopyRight © 2001 All Rights Reserved