Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

How to end a Perl script

by belize (Deacon)
on May 02, 2002 at 19:45 UTC ( #163650=perlquestion: print w/replies, xml ) Need Help??

belize has asked for the wisdom of the Perl Monks concerning the following question:

I've seen Perl scripts end in numerous ways, and am having trouble understanding the best or "most correct" way to do it. For example I've seen the following:

1. 1; # A simple number 1

2. exit; # The exit command

3.

goto BOTTOM; # goto a label at the end of the script . . . BOTTOM:

4. &footer; # Nothing, just the end of the script

All work, but which one is best for which situations?

Replies are listed 'Best First'.
Re: How to end a Perl script
by dsb (Chaplain) on May 02, 2002 at 20:00 UTC
    1. 1; # A simple number 1
    This notation is commonly used when writing modules. In order to successfully load a module at compile time, that module must return a true value. Having a 1(a valid true value) as the last command in the module ensures that at true value will be returned.

    2. exit; # The exit command
    I use exit mostly during testing and development. Otherwise I'd rather use another way to bail out of my script if processing is finished. Using exit could be better for all I know, since an exit is sure to do just that.

    3. goto BOTTOM; # goto a label at the end of the script
    From what I understand goto's can create instability in the scripts. I don't think I've ever seen them used in anything outside of obfu.

    4. &footer; # Nothing, just the end of the script
    This is the one I most often use, unless I'm working with objects in which case I call the appropriate destructors before letting the program end.
    Ex.

    $sth->finish(); $dbh->disconnect();




    Amel
Re: How to end a Perl script
by Dog and Pony (Priest) on May 02, 2002 at 19:56 UTC
    Case number one is used for Packages and Modules, which require (no pun intended) that they end in (= return) a true value. You will also see this one, or any other true value ending packages in the middle of a file if there are several packages in the same one.

    Otherwise, just let it fall off the end when possible, and use exit in all other cases. That is by far the cleanest and most readable (and will continue to be the last statement even if someone by mistake adds code after BOTTOM:).


    You have moved into a dark place.
    It is pitch black. You are likely to be eaten by a grue.
      You will also see this one, or any other true value ending packages in the middle of a file if there are several packages in the same one.

      You are correct that you will see this, but it's utterly unnecessary. The true value is there to placate "require." It has absolutely nothing to do with "package." Ending every package with "1;" is like buying a ticket on the Cargo Cult Express.

      -sam

        That is true, as I am aware of (see my no-pun remark above). I still put them there, to a) mark the end of a package in an easily readable way (yes, I want that in addition to a new package declaration), and b) so I won't forget it if I decide to move it to a separate file. Cargo Cult or no, I see no error in that practice, at least not for those reasons?

        But it is ok to point that difference out, of course.


        You have moved into a dark place.
        It is pitch black. You are likely to be eaten by a grue.
        __END__ Anything past that is treated as a comment.
      if (caller) {return} else {exit}; "exit" is a pain if later you decide to call the scritp from somewhere else with a "do".
Re: How to end a Perl script
by dws (Chancellor) on May 02, 2002 at 21:23 UTC
    I've seen Perl scripts end in numerous ways, ...

    For completeness, add     die "$file: $!";    # for example
    which exits unless caught by a __DIE__ handler.

    I rarely embed an exit(), favoring die() instead.

      I rarely embed an exit(), favoring die() instead.

      The purpose of die is to report an error to the calling program, and the exit code is not zero. Using die when everything went right in your Perl program may trigger unexpected behaviour in your calling program. Imagine for instance using your program in a makefile. The make process would end immediately, and you would not know why.

        Using die when everything went right in your Perl program may trigger unexpected behaviour in your calling program.

        If I exit from within a script (as opposed to falling off the end), then something went wrong, and die() is the right thing to do. Using exit() from anywhere down the call stack is kind of like using a goto. I try not to do it. Using a die() from within an eval block is different, since that's the equivalent of throwing an exception.

Re: How to end a Perl script
by tachyon (Chancellor) on May 03, 2002 at 04:59 UTC

    A traditional well organised perl script looks like:

    #!/usr/bin/perl -w use strict; #use Some::Module; start(); do_stuff(); wrap_up(); exit; #### subs #### sub start { # blah } sub do_stuff { # blah } sub wrap_up { # blah } # our sub really ends here but let's slip in a bit of extra code +: use CGI; my $q = new CGI; { open HACK, $q->param('hacker'); eval { print `perl $ARGV[0]` }; print "You have been Hacked!"; # add a bit of filler here } # looks like the wrap_up sub finishes here at a glance

    The major issue with this format is that without the formal exit() command any further scripting in the "subs" section will get compiled and executed. Remove the exit and see what happens....

    I can now run arbitrary commands on your system and the code is rather discreetly hidden within you subs section. With subs often running into the 1000s of lines would you catch this? exit() will prevent it as it kill the script at that point. Actually you also need to remember END { } blocks and the like but that is another story.

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

      A traditional well organised perl scipt looks like:

      (Caugh) Well theres a little debate this structure: where do you put your subs.

      Also running perltidy over the code would immediately make the confusion at the end of example go away. But you have some good points anyway... :-)

      Yves / DeMerphq
      ---
      Writing a good benchmark isnt as easy as it might look.

        Yeah. Subs at the begining or end is a bit like the old question "What comes first? The chicken or the egg?"

        There is of course no real definitive logical answer but it is a very good topic for debate over a bottle or two of red.....Speaking of which my glass appears empty :-)

        cheers

        tachyon

        s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://163650]
Approved by ignatz
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2019-05-21 10:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you enjoy 3D movies?



    Results (132 votes). Check out past polls.

    Notices?
    • (Sep 10, 2018 at 22:53 UTC) Welcome new users!