16. Exit

The exit function is used to immediately terminate the program. It can be called with an optional exit status, which is an integer value indicating the reason for the exit. Here are a few examples.

16.1 Basic usage

print "Before exit\n";
exit;
print "After exit\n"; # This line won't be executed

16.2 Exiting with a specific exit status

exit(1); # Exit with status 1, indicating some kind of error condition.

16.3 Exiting with a message

The die function is often used for error handling in Perl. It prints the given message to STDERR and then exits the program with a non-zero exit status (usually 1). This is commonly used to indicate errors or exceptional conditions.
die "An error occurred: Unable to open file\n";

16.4 Exiting from a block

In this example is not only the subroutine test terminated but the whole program.
sub test {
    # Some code
    exit;  # Exit from the subroutine
    # Code after exit won't be executed
}
test();
print("ok"); # This line won't be executed
However, an END block will be executed!
END {
    print "END block: this is executed at the end of the program.\n";
}

sub test {
    # Some code
    exit;  # Exit from the subroutine
    # Code after exit won't be executed
}
test();
# The END block will be executed, but the next command won't
print("ok"); 

16.5 Extract exit status

Save the following code into the file 'test.pl'
sub test {
    # Some code
    print("Hello\n");
    exit(5); # Exit from the subroutine with status 5
}
test();
Save the following code in the file 'extract_status.pl' (that invokes the file 'test.pl') and run it.
system("perl /home/reinier/test.pl"); # Choose your own path!
$exit_status = $? >> 8;
print("Exit status: $exit_status\n"); # Prints 5