Perl goto语句用法详细介绍

2021年3月28日15:32:51 发表评论 1,105 次浏览

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

语法如下:

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

在上面的语法中,goto语句将指示编译器立即跳转到标记为LABEL的语句。这里的label是一个用户定义的标识符,它指示目标语句。紧接在' label: '之后的语句是目标语句。

goto

Perl中的goto语句有三种形式——标签、表达式和子例程。

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

语法如下:

goto LABEL

goto EXPRESSION

goto Subroutine_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表达式:表达式也可以用来调用特定的标签,并将执行控制传递给该标签。当传递给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的子例程:也可以使用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

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: