Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the usefulness of CHECK, UNITCHECK and INIT blocks in Perl?

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 ENDs 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.

like image 900
friedo Avatar asked Nov 04 '09 03:11

friedo


People also ask

Which of the following blocks will get executed when we compile the Perl code?

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.

What is the difference between use and require in Perl?

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.

What is Perl end?

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.


2 Answers

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)

like image 118
DVK Avatar answered Oct 03 '22 15:10

DVK


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.

like image 31
mob Avatar answered Oct 03 '22 14:10

mob