What is the difference between function call and goto &NAME in Perl?

依然范特西╮ 提交于 2019-12-12 11:17:11

问题


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,

  1. What is the real difference between goto &NAME and normal function call in Perl?
  2. When we use goto &NAME?

Can anyone please explain with example.

Thanks in advance.


回答1:


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().



来源:https://stackoverflow.com/questions/40714465/what-is-the-difference-between-function-call-and-goto-name-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!