I'm reading Perl which is quite interesting. But while reading goto from here in Perl I got a doubt.
I know that goto statement has three types.
goto LABEL.
goto EXPR.
goto &NAME.
But in this three types, what is the use of third one goto &NAME
?
This is also seems to be like a function call.
Then,
- What is the real difference between
goto &NAME
and normal function call
in Perl?
- When we use goto &NAME?
Can anyone please explain with example.
Thanks in advance.
It says in the goto page
The goto &NAME
form is quite different from the other forms of
goto
. In fact, it isn't a goto in the normal sense at all, and
doesn't have the stigma associated with other gotos.
Then follows the answer to your question
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 @_
.
With a normal function call the execution continues on the next line after the function exits.
The rest of that paragraph is well worth reading as well, and answers your second question
This is used by AUTOLOAD
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 the goto
, not even caller
will be able to tell that this routine was called first.
A basic example. With a subroutine deeper
defined somewhere, compare
sub func_top {
deeper( @_ ); # pass its own arguments
# The rest of the code here runs after deeper() returns
}
with
sub func_top {
goto &deeper; # @_ is passed to it, as it is at this point
# Control never returns here
}
At the statement goto &deeper
the sub func_top
is exited. So after deeper
completes, the control returns to after the func_top
call.
In a sense, func_top
is replaced by deeper
.
Trying to pass arguments with goto &func
results in errors, even just for goto &deeper()
.