12.6. Automating Module Clean-UpProblemYou need to create setup code and clean-up code for a module that gets called automatically, without user intervention. SolutionFor setup code, put executable statements outside subroutine definitions in the module file. For clean-up code, use an END subroutine in that module. DiscussionIn some languages, the programmer must call a module's initialization code before any of that module's regular functions can be safely accessed. Similarly, when the program is done, the programmer may have to call module-specific finalization code. Not so in Perl. For per-module initialization code, executable statements outside of any subroutines in your module suffice. When the module is loaded in, that code runs right then and there. The user never has to remember to do this, because it's done automatically. Now, why would you want automatic clean-up code? It depends on the module. You might want to write a shutdown message to a logfile, tell a database server to commit any pending state, refresh a screen, or return the tty to its original state. Suppose you want a module to log quietly whenever a program using it starts up or finishes. Add code in an END subroutine to run after your program finishes: $Logfile = "/tmp/mylog" unless defined $Logfile; open(LF, ">>$Logfile") or die "can't append to $Logfile: $!"; select(((select(LF), $|=1))[0]); # unbuffer LF logmsg("startup"); sub logmsg { my $now = scalar gmtime; print LF "$0 $$ $now: @_\n" or die "write to $Logfile failed: $!"; } END { logmsg("shutdown"); close(LF) or die "close $Logfile failed: $!"; }
The first part of code, outside any subroutine declaration, is executed at module load time. The module user doesn't have to do anything special to make this happen. Someone might be unpleasantly surprised, however, if the file can't be accessed, since the
END routines work like exit handlers, such as Uncaught signals are a different matter, however. Death by signal does not run your exit handlers. The following pragma takes care of them: use sigtrap qw(die normal-signals error-signals);
END also isn't called when a process polymorphs itself via the See Also
The standard Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|