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

Hello,
I've noticed that not all scripts use exit; at the end of the script.

Also, I see some scripts end with a number 1;

Can someone explain the proper usage of these?
(everything I've read until now seems to skip over this)

Replies are listed 'Best First'.
Re: using exit and number 1 at end of file
by The Mad Hatter (Priest) on Jun 08, 2003 at 15:04 UTC
    In Perl you don't need to explicitly exit as it will clean up everything for you. The "scripts" you see end with 1; are probably modules. All modules, so that use/require-ing them works, should return a true value. The easiest way to ensure this is by putting a true value at the very end of the file. 42;, for example, would also have the same effect.
      ... because all values unequal 0 are TRUE in perl ...

        If you neglect overloading, all values other than "0", "", (), or undef are true. Equality to zero has nothing to do with it. Consider these:

        my @zeroes = qw( zero 0ButTrue 00 ); for my $z (@zeroes) { print "'$z' ", $z == 0 ? 'is ' : 'is not ', "equal to zero.\n"; print "'$z' ", $z ? 'is ' : 'is not ', "true.\n\n"; }
        With overloading, it is even possible to get an object which is both not equal to zero and false.
        package C; use overload 'bool' => sub { 0 }; use overload '==' => sub { 0 }; sub new { bless {} } package main; my $c = C->new; print "\$c is not equal to zero.\n" unless $c == 0; print "\$c is not true.\n" unless $c;

        -sauoq
        "My two cents aren't worth a dime.";
        
        Non-zero return values are useful when you're using perl in a shell script, where a zero exitcode means 'true' and non-zero exitcodes generally signal various kinds of error condition.

        For example, in Bash you might want to do:

          if findfile.pl; then (something) fi

        and make findfile.pl return >0 if it doesn't find a file.

        Zarni-oh-no-this-is-PERLmonks-isn't-it-woop
        ...except for undef.
Re: using exit and number 1 at end of file
by TexasTess (Beadle) on Jun 09, 2003 at 08:11 UTC
    At work we commonly use "exit" as a method of telling the calling party the status of the exit. exit 0 is normal, exit -1 on an error. We have various other programs written in other languages that call perl scripts. If they get a negative value in the exit they know there was an issue with the script and report it in a log or something similar. The values are arbitrary, it all depends on what you expect to be an error free exit versus what you expect to indicate an error.

    TexasTess
    It's all about love; What you'd do to love, and what you'd love to do -- Katherine Moody