Perl goto Statement
Perl has three forms of goto: goto LABEL, goto EXPR, and goto &NAME:
Number | goto Type |
---|---|
1 | goto LABEL finds the statement labeled as LABEL and resumes execution from there. |
2 | goto EXPR The goto EXPR form is just a generalized form of goto LABEL. It expects the expression to yield a label name and jumps to that label. |
3 | goto &NAME replaces the currently running subroutine with a call to a named subroutine. |
Syntax
The syntax is as follows:
goto LABEL
or
goto EXPR
or
goto &NAME
Flowchart
Example
The following two examples skip the output when the variable $a is 15.
Here is a common goto example:
Example
#/usr/bin/perl
$a = 10;
LOOP:do
{
if( $a == 15){
# Skip iteration
$a = $a + 1;
# Using goto LABEL form
print "Skipped output \n";
goto LOOP;
print "This line will not be executed \n";
}
print "a = $a\n";
$a = $a + 1;
}while( $a < 20 );
Executing the above program, the output is:
a = 10
a = 11
a = 12
a = 13
a = 14
Skipped output
a = 16
a = 17
a = 18
a = 19
The following example uses the goto EXPR form. We use two strings and concatenate them with a dot (.).
Example
$a = 10;
$str1 = "LO";
$str2 = "OP";
LOOP:do
{
if( $a == 15){
# Skip iteration
$a = $a + 1;
# Using goto EXPR form
goto $str1.$str2; # Similar to goto LOOP
}
print "a = $a\n";
$a = $a + 1;
}while( $a < 20 );
Executing the above program, the output is:
a = 10
a = 11
a = 12
a = 13
a = 14
a = 16
a = 17
a = 18
a = 19