goto
- goto EXPR
- goto &NAME
The
goto LABEL
form finds the statement labeled with LABEL and resumes execution there. It can't be used to get out of a block or subroutine given tosort
. It can be used to go almost anywhere else within the dynamic scope, including out of subroutines, but it's usually better to use some other construct such aslast
ordie
. The author of Perl has never felt the need to use this form ofgoto
(in Perl, that is; C is another matter). (The difference is that C does not offer named loops combined with loop control. Perl does, and this replaces most structured uses ofgoto
in other languages.)The
goto EXPR
form expects to evaluateEXPR
to a code reference or a label name. If it evaluates to a code reference, it will be handled likegoto &NAME
, below. This is especially useful for implementing tail recursion viagoto __SUB__
.If the expression evaluates to a label name, its scope will be resolved dynamically. This allows for computed
goto
s per FORTRAN, but isn't necessarily recommended if you're optimizing for maintainability:- goto ("FOO", "BAR", "GLARCH")[$i];
As shown in this example,
goto EXPR
is exempt from the "looks like a function" rule. A pair of parentheses following it does not (necessarily) delimit its argument.goto("NE")."XT"
is equivalent togoto NEXT
. Also, unlike most named operators, this has the same precedence as assignment.Use of
goto LABEL
orgoto EXPR
to jump into a construct is deprecated and will issue a warning. Even then, it may not be used to go into any construct that requires initialization, such as a subroutine or aforeach
loop. It also can't be used to go into a construct that is optimized away.The
goto &NAME
form is quite different from the other forms ofgoto
. In fact, it isn't a goto in the normal sense at all, and doesn't have the stigma associated with other gotos. Instead, it exits the current subroutine (losing any changes set by local()) and immediately calls in its place the named subroutine using the current value of @_. This is used byAUTOLOAD
subroutines that wish to load another subroutine and then pretend that the other subroutine had been called in the first place (except that any modifications to@_
in the current subroutine are propagated to the other subroutine.) After thegoto
, not evencaller
will be able to tell that this routine was called first.NAME needn't be the name of a subroutine; it can be a scalar variable containing a code reference or a block that evaluates to a code reference.