This code blocks are executed by perl itself as something similar to subroutine so calling return just ends block execution and value is ignored. If you want to exit program with value use exit.
#!/usr/bin/perl
use 5.010;
BEGIN {exit 0}
say "start";
return 1;
Also there is another way to use $?
but acording to perldoc it is working only for END
blocks.
[ OP comment ]
@teodozjan rightly mentions that you can somehow interrupt the compiling (resp. start up) process by calling exit
in the BEGIN
(resp. INIT
) block.
It should be noted that exit 0
has quite a different effect than return 0
though :
return 0
is Perl's syntax to say "exit from this function block and yield this value to your caller". It looks like the return value has no impact when you call it from a BEGIN
or INIT
block, but you still get the "stop function execution here" part, and Perl keeps running (the compilation / start up keeps on going).
exit 0
is Perl's syntax to say "halt the whole program now and yield this value as the process' exit status". It will work the same way from inside a BEGIN
or INIT
block : Perl will immediately stop compiling / executing your program, and the exit status (eg : $?
in your shell) will be 0
.
Btw, 0
is the conventional exit status to say "everything went fine". If you want to signal an error, you should somehow exit
with a non-zero status (or call croak()
or die()
: exit status will be 255).
BEGIN/INIT
block. Did I miss something ?