📜  珀尔 | goto 语句

📅  最后修改于: 2022-05-13 01:55:47.652000             🧑  作者: Mango

珀尔 | goto 语句

Perl 中的goto语句是跳转语句,有时也称为无条件跳转语句。 goto语句可用于在函数内从任意位置跳转到任意位置。
句法:

LABEL:
Statement 1;
Statement 2;
.
.
.
.
.
Statement n;
goto LABEL;

在上述语法中, goto语句将指示编译器立即转到/跳转到标记为 LABEL 的语句。这里的 label 是一个用户定义的标识符,表示目标语句。紧跟在“标签:”之后的语句是目标语句。
去
Perl 中的goto语句有三种形式——标签、表达式和子程序。

  1. 标签:它会简单地跳转到标有标签的语句,并从该语句继续执行。
  2. 表达式:在这种形式中,会有一个表达式,它会在评估后返回一个标签名称,goto 会使其跳转到带标签的语句。
  3. 子程序: goto 会将编译器从当前运行的子程序转移到给定名称的子程序。

句法:

goto LABEL

goto EXPRESSION

goto Subroutine_Name

goto using LABEL name: LABEL name 用于跳转到代码中的特定语句,并将从该语句开始执行。虽然它的范围是有限的。它只能在调用它的范围内工作。
例子:

# Perl program to print numbers 
# from 1 to 10 using goto statement 
  
# function to print numbers from 1 to 10 
sub printNumbers() 
{ 
    my $n = 1; 
label: 
    print "$n "; 
    $n++; 
    if ($n <= 10) 
    {
        goto label;
    }
} 
    
# Driver Code
printNumbers(); 
输出:
1 2 3 4 5 6 7 8 9 10

goto using Expression:表达式也可用于调用特定标签并将执行控制传递给该标签。此表达式在传递给goto语句时,计算生成一个标签名称,并从该标签名称定义的该语句继续执行进一步的执行。
例子:

# Perl program to print numbers 
# from 1 to 10 using the goto statement 
  
# Defining two strings 
# which contain 
# label name in parts
$a = "lab";
$b = "el";
  
# function to print numbers from 1 to 10 
sub printNumbers() 
{ 
    my $n = 1; 
label: 
    print "$n "; 
    $n++; 
    if ($n <= 10) 
    {
        # Passing Expression to label name
        goto $a.$b;
    }
} 
    
# Driver Code
printNumbers(); 
输出:
1 2 3 4 5 6 7 8 9 10

goto using Subroutine:也可以使用goto语句调用子例程。该子例程从另一个子例程中调用,或根据其用途单独调用。它保存在调用语句旁边要执行的工作。此方法可用于递归调用函数以打印一系列或一系列字符。
例子:

# Perl program to print numbers 
# from 1 to 10 using goto statement 
  
# function to print numbers from 1 to 10 
sub label
{
    print "$n ";
    $n++;
      
    if($n <= 10)
    {
        goto &label;
    }
}
  
# Driver Code
my $n = 1;
label(); 
输出:
1 2 3 4 5 6 7 8 9 10