Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

break out of a subroutine

Tags:

perl

what is the best way to break out of a subroutine & 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";

}
like image 695
user_78361084 Avatar asked Dec 13 '22 16:12

user_78361084


2 Answers

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 ...
like image 193
justintime Avatar answered Jan 06 '23 13:01

justintime


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.

like image 41
Nee Avatar answered Jan 06 '23 14:01

Nee