I know what they all do, but have never found myself in a situation where I've needed any of them. I've used BEGIN
blocks on many occasions and END
s once in a while. BEGIN
is especially useful when you need to tweak the environment before code gets run, and I've used END
in certain debugging situations to trap important state information for hard-to-track-down fatal errors.
Have you ever used CHECK
, UNITCHECK
or INIT
? If so, what for? And would a BEGIN
block not have sufficed for some reason?
The documentation for the blocks is on PerlDoc.
Every BEGIN block is executed after the perl script is loaded and compiled but before any other statement is executed. Every END block is executed just before the perl interpreter exits. The BEGIN and END blocks are particularly useful when creating Perl modules.
The differences are many and often subtle:use only expects a bareword, require can take a bareword or an expression. use is evaluated at compile-time, require at run-time. use implicitly calls the import method of the module being loaded, require does not.
The eof() function is used to check if the End Of File (EOF) is reached. It returns 1 if EOF is reached or if the FileHandle is not open and undef in all other cases.
An interesting use of CHECK blocks is in "Advanced Perl programming" by Simon Cozens (O'Reilly) in Chapter 1, in "Doing things later with CHECK" section. He shows how to implement "final" java-like attribute
Also, Devel::Sub::Trace uses INIT blocks to incert traces (this info is from POD for Devel::Hook which is a module used for working with those named blocks)
I had a package import
function which would do some heavy duty processing and then make an eval
call. How do you debug something like that? The import function gets run when you use
the module, which takes place at compile time (like it was inside a BEGIN block). For some reason (I think it was because I needed to pass parameters to import
with heredoc notation, but it could have been something else), it wasn't good enough to say require Module; Module->import(@args)
.
So my workaround was to build the string for eval
in import
, and save it another variable.
Then I ran the eval
in an INIT
block. When you ran the debugger, the very first execution point was at the start of the INIT
block and I could use the debugger to step through the eval
statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With