Goto statements in Perl help the program jump to another point in the code unconditionally. The new point can be anywhere within the same function.
The goto
statement makes the compiler jump to LABEL 1
in the syntax below. LABEL 1
is the user-defined identifier that indicates the target statement. The code block following the label is the destination.
LABEL 1:
## code block
#### .
# .
# .
## goto statement somewhere in the code block
goto LABEL 1;
There are three types of goto
statements in Perl:
goto
statement jumps to the statement marked as the label and continues execution from that statement. This type’s scope is limited. It can only work in the function in which it is called.The code below demonstrates how we can use goto
statements.
# Goto example# type 1: labels# function to print numbers from 1 to 10sub printNumbers_label(){my $num = 1;label_1:print "$num ";$num++;if ($num <= 10){goto label_1;}}# Driver Codeprint "Type 1: Label\n";printNumbers_label();# type 2: expressions# function to print numbers from 1 to 10sub printNumbers_2(){$a = "lab";$b = "el_2";my $num = 1;label_2:print "$num ";$num++;if ($num <= 10){# Passing Expression to label namegoto $a.$b;}}# Driver Codeprint "\nType 2: Expression\n";printNumbers_2();# type 3: subroutines# function to print numbers from 1 to 10sub label_3{print "$num ";$num++;if($num <= 10){goto &label_3;}}# Driver Codeprint "\nType 3: Subroutine\n";my $num = 1;label_3();
As explained in the types above:
Free Resources