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

I am reading Perl, which is pretty interesting. But when reading goto from here in Perl, I had a doubt.

I know that goto instruction has three types.

goto LABEL.

goto EXPR.

goto & NAME.

But in these three types, what is the use of the third goto &NAME ? It also looks like a function call. Then,

  • What is the difference between goto &NAME and normal function call in Perl?
  • When do we use goto & NAME?

Can someone explain an example.

Thanks in advance.

+5
source share
1 answer

He says in the goto page

The goto &NAME form is very different from other goto forms. In fact, this is not a reception in the normal sense, and does not have the stigma associated with other gotos.

Then the answer to your question follows.

Instead, it terminates the current routine (losing any changes set to local() ) and immediately calls the named routine in its place using the current value of @_ .

When a normal function is called, execution continues on the next line after the function exits.

The rest of this paragraph is also worth reading, and also answers your second question.

This is used by AUTOLOAD routines that want to load another routine, and then pretend that the second routine was called first (except that any changes to @_ in the current routine propagate to another routine.) After goto not even caller can tell that this procedure was called first.


The main example. Having defined the deeper subroutine 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 } 

The goto &deeper ends with sub func_top . Thus, after deeper completes, control returns after calling func_top . In a way, func_top is replaced by deeper .

Attempting to pass arguments using goto &func will result in errors, even for goto &deeper() .

+10
source

Source: https://habr.com/ru/post/1260063/


All Articles