On Wed, Jul 21, 2010 at 07:18, Mimi Cafe <mimic...@googlemail.com> wrote:
> Hi Rob
>
> I take care of everything that needs (execution errors) to be done within my 
> sub. Perhaps this may help explain what I have:
>
> A the beginning of my program I test to see what needs to be done, and if a 
> conditional evaluates to true, then a sub is called to work and that is it. 
> The program should not continue once a sub ends executing.
>
>
> If ($foo){
>   my_sub_foo();
>   # Is the program going to continue from here once sub foo has ended and I 
> have not called exit here or in the sub?
> }
> elsif ($bar){
>    my_sub_bar();
> }
> else {
>
>   my_other_sub();
> }
>
> sub foo {
>    do everything that needs to be done.
>    # I expect the program to end here once the sub has completed executing.
> }
>
> sub bar {
>    do everything that needs to be done.
>    # I expect the program to end here once the sub has completed executing.
> }
>
> Sub my_other_sub {
>   ...............
>   ...............
>   # I expect the program to end here once the sub has completed executing.
> }
>
> As seen above, if a condition is met, then a sub is called to deal with it 
> and the program should exit. My question is: what happens if I don't call 
> exit in the last line of the sub or after calling the sub? Is the program 
> going to continue running once the sub has ended?
>
> If my program will continue to evaluate the rest of the program, then is it 
> efficient to call exit one time at the end of the program or call exit as the 
> last line of each subroutine to ensure the program ends there?
snip

Yes, the program will run any code after your if/elsif/else statement:

#!/usr/bin/perl

use strict;
use warnings;

foo();

sub foo {
        print "foo\n";
}

print "bar\n";

But since you don't have any directly executable code after the if
statement (subroutine definitions don't execute), you shouldn't have a
problem.  A return or an exit at the end of what you consider to be
your code is safer and is a good marker for other readers that the
this is where the program ends.  Because you are using the style of
code where functions follow the main part of the code, it will also
prevents stray code from executing:

#!/usr/bin/perl

use strict;
use warnings;

foo();
exit; #the code will no longer print "bar\n"

sub foo {
        print "foo\n";
}

print "bar\n";


-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to