Perl Tutorial Perl References

Perl - goto Statement



In Perl, goto is a jump statement and sometimes also referred as unconditional jump statement. Perl supports goto statement in three forms - Label, Expression, and Subroutine.

  • Label - The goto LABEL jumps to the statement labeled with LABEL and will continue the execution from that statement.
  • Expression - The goto EXPR expects the EXPR to return a label name and then jumps to that labeled statement.
  • Subroutine - The goto &SubName will transfer the compiler to the named subroutine from the currently running subroutine.

Syntax

//goto with Label
goto label;

//goto with Expression
goto EXPR;

//goto with Subroutine
goto &SubName;

In the above syntax, label is a user-defined identifier and it can be set anywhere in the Perl program above or below to goto statement.

Flow Diagram:

Perl goto

Example: goto with Label name

In the example below, the goto statement is used to display message based on the value of variable x. The program first checks whether the variable x is even or odd and then goto statement is used to display the message based on even/odd assessment.

sub checkNumber {
  #passing argument
  $x = $_[0];

  if ($x%2 == 0) {
    goto evenNumber;
  } else {
    goto oddNumber;
  }
  
  evenNumber:
    #print the message and exit the function
    print("$x is an even number.\n");
    return; 
  oddNumber:
    #print the message and exit the function
    print("$x is an odd number.\n");
    return;  
}

checkNumber(10);
checkNumber(13);
checkNumber(-10);

The output of the above code will be:

10 is an even number.
13 is an odd number.
-10 is an even number.

Example: goto with Expression

In the example below, the goto statement is used with expression. The expression returns a label name and based on the expression value, the program jumps to that labeled statement.

sub checkEven {
  #passing argument
  $x = $_[0];

  $a = "Not";
  $b = "Even";

  #passing expression to label names
  if($x%2 == 0) {
    goto $b;
  } else {
    goto $a.$b;
  }
  
  Even: 
    print("$x is an even number.\n");
    return;  #return when even
  NotEven:
    print("$x is NOT an even number.\n");
    return;  #return when not even
}

checkEven(50);
checkEven(55);

The output of the above code will be:

50 is an even number.
55 is NOT an even number.

Example: goto with Subroutine

In the example below, the goto statement is used with subroutine.

sub SubName {
  while ($x < 5){
    $x++;
    print("x = $x \n");
    goto &SubName;
  }
}

SubName();

The output of the above code will be:

x = 1 
x = 2 
x = 3 
x = 4 
x = 5