use, BEGIN and what's Perl doing with them

Dieser Post wurde aus meiner alten WordPress-Installation importiert. Sollte es Darstellungsprobleme, falsche Links oder fehlende Bilder geben, bitte einfach hier einen Kommentar hinterlassen. Danke.

use-lines and BEGIN-blocks are not processed like they appear within a file.

Let's try out this sample script:


use Mod::One;BEGIN { use Mod::Two; print 1; use Mod::Three;}END { print 7;}use Mod::Four;print 2;use Mod::Five;

print 3;


print 6;

sub a { print 4; use Mod::Six; print 5;}

This file isn't processed in the order of it's lines. Actually processing is done this way:

# use-lines and BEGIN-blocks are processed in order, but everything else is ignored:use Mod::One;BEGIN { use Mod::Two; use Mod::Three; # will be loaded at the beginning of the BEGIN block before source is executed print 1;}use Mod::Four;use Mod::Five;use Mod::Six; # Any uses are processed at compile time before anything else is executed

print 2; # Statements mixed in use lines are executed after all use's are doneprint 3;print 4; # from sub aprint 5; # from sub aprint 6;print 7; # from END

Only few lines are running if this file is used within a mod_perl or FastCGI installation. The second request will only execute these lines:
print 2;print 3;print 4; # from sub aprint 5; # from sub aprint 6;
The END-block (containing "print 7;") won't be executed until the Apache or FastCGI process exits.

Every Perl source file should be written in the same order Perl is executing the source:

  1. #!/usr/bin/perl (if required) at the first line
  2. use Modules; required to be loaded before the BEGIN block
  3. BEGIN-block (if necessary, avoid it if every possible!)
  4. use Modules; which require the BEGIN block to be loaded
  5. Script source
Basic rules:
  1. Don't ever write any source before or within use-lines and the BEGIN block (except source running within the BEGIN block).
  2. Requiring a BEGIN block to load other modules is bad.
Visit Perldoc for the full Perl documentation of BEGIN, INIT, END.

If you're unsure about Perl's processing of your file, use Devel::Trace (perl -d:Trace or add some debug statements (but even they might not be executed in the order of their appearance).


Noch keine Kommentare. Schreib was dazu

Schreib was dazu

Die folgenden HTML-Tags sind erlaubt:<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>