Thursday, March 17, 2011

Perl: BEGIN and END


Perl ScriptOutput
BEGIN {
    print "Birth of a process...\n";
}

print "Life of a process...\n";
die "Murder of a process...\n";

END {
    print "Death of a process...\n";
}
Birth of a process...
Life of a process...
Murder of a process...
Death of a process...
bash-2.03$ 
bash-2.03$ 
 
Perl ScriptOutput
BEGIN {
    print "Birth still runs !\n";
}

This won't compile;

END {
    print "Death still runs !\n";
}

Birth still runs !
Can't locate object method "This" via package "won::t"
(perhaps you forgot to load "won::t"?) at 1.pl line 5.
Death still runs !

 
Perl ScriptOutput
die "Bye";

END   { print "End 1\n"    }
BEGIN { print "Begin 1\n"; }
END   { print "End 2\n"    }
BEGIN { print "Begin 2\n"; }

Begin 1
Begin 2
Bye at 1.pl line 1.
End 2
End 1

BEGIN

Run some code as soon as it has all been read in by the parser and before the rest compiles.

END

Run some code as late as possible. When the interpreter is ready to shut down.

No comments: