2011-01-09 73 views
0

什么是突破子程序&继续处理脚本的其余部分的最好方法?突破子程序

#!/usr/bin/perl 
use strict; 
use warnings; 

&mySub; 

print "we executed the sub partway through & continued w/ the rest 
of the script...yipee!\n"; 

sub mySub{ 

    print "entered sub\n"; 

    #### Options 
    #exit; # will kill the script...we don't want to use exit 
    #next; # perldoc says not to use this to breakout of a sub 
    #last; # perldoc says not to use this to breakout of a sub 
    #any other options???? 

    print "we should NOT see this\n"; 

} 
+14

`return`有什么问题? – 2011-01-09 23:04:38

+0

我不知道......它是应该完成的方式吗? – 2011-01-09 23:06:53

回答

5

在说明了一个子程序中返回时的明显的最佳方式的代价......

return 

除非存在问题的一些隐藏的细微之处这不是摆明了

编辑 - 也许我看到你在

得到什么

如果你写一个循环,然后走出循环的一个有效办法是使用last

use strict ; 
    use warnings ; 
    while (<>) { 
     last if /getout/ ; 
     do_something() ; 
    } 

如果你重构这个,你可能最终得到一个使用最后走出子程序。

use strict ; 
    use warnings ; 
    while (<>) { 
     process_line() ; 
     do_something() ; 
    } 

    sub process_line { 
     last if /getout/ ; 
     print "continuing \n" ; 
    } 

这意味着你正在使用last,你应该使用return,如果你在的地方wanings你的错误:

Exiting subroutine via last at ..... some file ... 
0

不要使用退出中止子程序,如果有任何有人可能想要捕捉发生的任何错误的机会。使用die,可以被eval困住。