What is goto in Perl?

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.

Syntax

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;

Types of goto statements

There are three types of goto statements in Perl:

  1. Label:
    The 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.
  2. Expression:
    We compute an expression that results in a label name to which the compiler jumps.
  3. Sub-routine:
    The compiler is transferred to the subroutine named here, which is called from within another subroutine. The target subroutine contains the destination code. We can also use this method for recursion.

Code

The code below demonstrates how we can use goto statements.

# Goto example
# type 1: labels
# function to print numbers from 1 to 10
sub printNumbers_label()
{
my $num = 1;
label_1:
print "$num ";
$num++;
if ($num <= 10)
{
goto label_1;
}
}
# Driver Code
print "Type 1: Label\n";
printNumbers_label();
# type 2: expressions
# function to print numbers from 1 to 10
sub printNumbers_2()
{
$a = "lab";
$b = "el_2";
my $num = 1;
label_2:
print "$num ";
$num++;
if ($num <= 10)
{
# Passing Expression to label name
goto $a.$b;
}
}
# Driver Code
print "\nType 2: Expression\n";
printNumbers_2();
# type 3: subroutines
# function to print numbers from 1 to 10
sub label_3
{
print "$num ";
$num++;
if($num <= 10)
{
goto &label_3;
}
}
# Driver Code
print "\nType 3: Subroutine\n";
my $num = 1;
label_3();

As explained in the types above:

  • Type 1: The label takes execution directly to the code block which has the label as its name.
  • Type 2: Expressions are computed before execution is taken to the block which has the computed name.
  • Type 3: The execution is shifted to the mentioned subroutine.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved