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 with label names to display message according to provided argument.

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

  if($x < 0){
    goto notNatural;
  } elsif($x%2 == 0) {
    goto evenNatural;
  } else {
    goto oddNatural;
  }
  
  notNatural: 
    print("$x is not a natural number.\n");
    return;  #return when not natural
  evenNatural:
    print("$x is an even natural number.\n");
    return;  #return when even natural
  oddNatural:
    print("$x is an odd natural number.\n");
    return;  #return when odd natural
}

checkNaturalNumber(10);
checkNaturalNumber(13);
checkNaturalNumber(-10);

The output of the above code will be:

10 is an even natural number.
13 is an odd natural number.
-10 is not a natural number.

Example: goto with Expression

In the example below, the goto statement is used with expression. The expression return a label name and then 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 

5