1

I'm browsing a (home written) Perl code base, and I see :

# BEGIN blocks :
BEGIN {
    ... #do stuff
    return 1;
}

#INIT blocks :
INIT {
    ... #do stuff
    return 1;
}

I couldn't find any info on the effect (or lack thereof) of the return value in a BEGIN or INIT block.

My question :
Does the return value of a BEGIN or INIT block have any influence on a module's compilation or execution ?

2
  • perldoc.perl.org/…
    – teodozjan
    Commented Dec 3, 2014 at 9:31
  • @teodozjan : I read that, I didn't see any mention of a return value from within a BEGIN/INIT block. Did I miss something ?
    – LeGEC
    Commented Dec 3, 2014 at 9:52

2 Answers 2

1

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).

0
0

I tried the following test case :

#file TestModule.pm :
package TestModule;

BEGIN {
    print "BEGIN -- TestModule\n";
    return 0; # guessing a value which would mean "something went wrong"
}

INIT {
    print "INIT -- TestModule\n";
    return 0; # guessing a value which would mean "something went wrong"
}

1;

#file test.pl :

#!/usr/bin/perl

use TestModule;

print "Hello!\n";

The test.pl script happily runs :

$ perl test.pl
BEGIN -- TestModule
INIT -- TestModule
Hello !

which leads me to think the return value has no effect.

I would just like a stronger confirmation.

Not the answer you're looking for? Browse other questions tagged or ask your own question.