goto &NAMEThe goto-LABEL
form finds the statement labeled with LABEL andresumes execution there. It can't be used to get out of a block orsubroutine given to sort
. It can be used to go almost anywhereelse within the dynamic scope, including out of subroutines, but it'susually better to use some other construct such as last
or die
.The author of Perl has never felt the need to use this form of goto
(in Perl, that is; C is another matter). (The difference is that Cdoes not offer named loops combined with loop control. Perl does, andthis replaces most structured uses of goto
in other languages.)
The goto-EXPR
form expects a label name, whose scope will be resolveddynamically. This allows for computed goto
s per FORTRAN, but isn'tnecessarily 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 afunction" rule. A pair of parentheses following it does not (necessarily)delimit its argument. goto("NE")."XT"
is equivalent to goto NEXT
.
Use of goto-LABEL
or goto-EXPR
to jump into a construct isdeprecated and will issue a warning. Even then, it may not be used togo into any construct that requires initialization, such as asubroutine or a foreach
loop. It also can't be used to go into aconstruct 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, anddoesn't have the stigma associated with other gotos. Instead, itexits the current subroutine (losing any changes set by local()) andimmediately calls in its place the named subroutine using the currentvalue of @_. This is used by AUTOLOAD
subroutines that wish toload another subroutine and then pretend that the other subroutine hadbeen called in the first place (except that any modifications to @_
in the current subroutine are propagated to the other subroutine.)After the goto
, not even caller
will be able to tell that thisroutine was called first.
NAME needn't be the name of a subroutine; it can be a scalar variablecontaining a code reference or a block that evaluates to a codereference.