Perl 中的函数调用和 goto &NAME 有什么区别?
What is the difference between function call and goto &NAME in Perl?
我正在阅读 Perl,这很有趣。但是在用 Perl 阅读 goto from here 时我有一个疑问。
我知道goto语句有3种类型
goto LABEL.
goto EXPR.
goto &NAME.
可是这三种中,第三种有什么用呢goto &NAME
?
这似乎也像是一个函数调用。
那么,
- Perl 中
goto &NAME
和普通 function call
之间的真正区别是什么?
- 当我们使用 goto &NAME?
谁能举例说明一下。
提前致谢。
它在 goto 页面上说
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.
然后是您问题的答案
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 @_
.
对于正常的函数调用,函数退出后在下一行继续执行。
该段的其余部分也很值得一读,并回答了您的第二个问题
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.
一个基本的例子。在某处定义了一个子例程 deeper
,比较
sub func_top {
deeper( @_ ); # pass its own arguments
# The rest of the code here runs after deeper() returns
}
与
sub func_top {
goto &deeper; # @_ is passed to it, as it is at this point
# Control never returns here
}
在语句 goto &deeper
处退出子 func_top
。所以在 deeper
完成后,控制 returns 到 func_top
调用之后。
从某种意义上说,func_top
被deeper
取代了。
尝试使用 goto &func
传递参数会导致错误,即使只是 goto &deeper()
。
我正在阅读 Perl,这很有趣。但是在用 Perl 阅读 goto from here 时我有一个疑问。
我知道goto语句有3种类型
goto LABEL.
goto EXPR.
goto &NAME.
可是这三种中,第三种有什么用呢goto &NAME
?
这似乎也像是一个函数调用。
那么,
- Perl 中
goto &NAME
和普通function call
之间的真正区别是什么? - 当我们使用 goto &NAME?
谁能举例说明一下。
提前致谢。
它在 goto 页面上说
The
goto &NAME
form 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.
然后是您问题的答案
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@_
.
对于正常的函数调用,函数退出后在下一行继续执行。
该段的其余部分也很值得一读,并回答了您的第二个问题
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 thegoto
, not evencaller
will be able to tell that this routine was called first.
一个基本的例子。在某处定义了一个子例程 deeper
,比较
sub func_top {
deeper( @_ ); # pass its own arguments
# The rest of the code here runs after deeper() returns
}
与
sub func_top {
goto &deeper; # @_ is passed to it, as it is at this point
# Control never returns here
}
在语句 goto &deeper
处退出子 func_top
。所以在 deeper
完成后,控制 returns 到 func_top
调用之后。
从某种意义上说,func_top
被deeper
取代了。
尝试使用 goto &func
传递参数会导致错误,即使只是 goto &deeper()
。