Ganapathy Ganapathy - 1 year ago 109
Perl Question

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

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.

  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.

Answer Source

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 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 runs after deeper() returns


sub func_top {        
    goto &deeper;  # @_ is passed to it

    # 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.

Passing arguments to a goto &func results in errors/warnings. Even just &deeper() gets errors.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download