免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4194 | 回复: 1

perl goto的不同用法 [复制链接]

论坛徽章:
0
发表于 2010-06-24 14:55 |显示全部楼层
先看一下官方的文档
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.

goto &subname 是先退出当前的过程然后执行 过程 subname,这样可以避免在使用 return subname 的时候在subname内部使用受到影响的一些变量
如:

  1. sub test1 {
  2.      print "This is test1 ";
  3.      print "\$/ is:" . $/;
  4. }
  5. sub test2 {
  6.        local $/ = '#';
  7.        goto &test1;
  8. }
  9. sub test3 {
  10.        local $/ = '#';
  11.        return test1();
  12. }
  13. print "call test2\n";
  14. test2();
  15. print "\ncall test3\n";
  16. test3();
复制代码

在查看 Export.pm模块时发现这个比较特殊的用法,感觉很好很强大

  1. sub export {
  2.   goto &{as_heavy()};
  3. }
复制代码

论坛徽章:
0
发表于 2010-06-24 16:37 |显示全部楼层
AUTOLOAD 就是利用 goto 实现的 proxy 效果
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP