The goto Operator
Although not for the faint of heart (nor for the pure of heart), Perl
does support a goto operator. There
are three forms: goto
LABEL, goto EXPR, and
goto
&NAME.
The goto
LABEL form finds the statement labelled with
LABEL and resumes execution there. It can’t
be used to jump into any construct that requires initialization, such
as a subroutine or a foreach loop.
It also can’t be used to jump into a construct that has been optimized
away (see Chapter 16). It can be used to go almost
anywhere else within the current block or any block in your dynamic
scope (that is, a block you were called from). You can even goto out of subroutines, but it’s usually
better to use some other construct. The author of Perl has never felt
the need to use the labelled form of goto in Perl (except to test that it
works).
The goto
EXPR form is just a generalization of
goto
LABEL. It expects the expression to produce
a label name, whose location obviously has to be resolved dynamically
by the interpreter. This allows for computed gotos per FORTRAN, but
isn’t necessarily recommended if you’re optimizing for
maintainability:
goto(("FOO", "BAR", "GLARCH")[$i]); # hope 0 <= i < 3
@loop_label = qw/FOO BAR GLARCH/;
goto $loop_label[rand @loop_label]; # random teleportIn almost all cases like this, it’s usually a far, far better
idea to use the structured control-flow mechanisms of next, last, or redo instead of resorting to a goto. For certain applications, a hash of references to functions or the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access