PERL Constructors and Destructors:
Perl has constructors and destructors that work at the module level as well as the class level. The module constructor is called the BEGIN block, while the module destructor is called the END block.
- The BEGIN Block
- The END Block
BEGIN BLOCK:
The BEGIN block is evaluated as soon as it is defined. Therefore, it can include other functions using do() or require statements. Since the blocks are evaluated immediately after definition, multiple BEGIN blocks will execute in the order that they appear in the script.
For Example (export.pl):
- Define a BEGIN block for the main package.
- Display a string indicating the begin block is executing.
- Start the Foo package.
- Define a BEGIN block for the Foo package.
The Perl code is (export.pl):
BEGIN { print("main\n"); } package Foo; BEGIN { print("Foo\n"); }
This program displays:
main Foo
END BLOCK:
The END blocks are the last thing to be evaluated. They are even evaluated after exit() or die() functions are called. Therefore, they can be used to close files or write messages to log files. Multiple END blocks are evaluated in reverse order.
END {
print("main\n");
}
package Foo;
END {
print("Foo\n");
}
This program displays:
Foo
Main
Note:
Signals that are sent to your script can bypass the END blocks. So, if your script is in danger of stopping due to a signal, be sure to define a signal-handler function. See Chapter 13, "Handling Errors and Signals," for more information.
No comments:
Post a Comment