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:
#!/usr/bin/perlThis file isn't processed in the order of it's lines. Actually processing is done this way: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;
a();
print 6;
sub a { print 4; use Mod::Six; print 5;}
#!/usr/bin/perlOnly few lines are running if this file is used within a mod_perl or FastCGI installation. The second request will only execute these lines:# 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
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:
- #!/usr/bin/perl (if required) at the first line
- use Modules; required to be loaded before the BEGIN block
- BEGIN-block (if necessary, avoid it if every possible!)
- use Modules; which require the BEGIN block to be loaded
- Script source
- Don't ever write any source before or within use-lines and the BEGIN block (except source running within the BEGIN block).
- Requiring a BEGIN block to load other modules is bad.
If you're unsure about Perl's processing of your file, use Devel::Trace (perl -d:Trace yourscript.pl) or add some debug statements (but even they might not be executed in the order of their appearance).
Noch keine Kommentare. Schreib was dazu