开发者

break out of a subroutine

what is the best way to break out of a subr开发者_运维问答outine & continue processing the rest of the script?

ie

#!/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";

}


At the expense of stating the obvious the best way of returning for a subroutine is ......

return

Unless there is some hidden subtlety in the question that isn't made clear

Edit - maybe I see what you are getting at

If you write a loop, then a valid way of getting out of the loop is to use last

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

If you refactor this, you might end up with a using last to get out of the subroutine.

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

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

This means you are using last where you should be using return and if you have wanings in place you get the error :

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


Don't use exit to abort a subroutine if there's any chance that someone might want to trap whatever error happened. Use die instead, which can be trapped by an eval.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜