2011-01-09 66 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困住。