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,
goto &NAME and normal function call in Perl?Can anyone please explain with example.
Thanks in advance.
It says in the goto page
The
goto &NAMEform 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.
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
AUTOLOADsubroutines 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 evencallerwill 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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With