Perl for Newbies - Part 3 - Modules and ObjectsPerl ModulesBEGIN and END

3.3. BEGIN and END

There are two special code blocks for perl modules - BEGIN and END. These blocks are executed when a module is first loaded, and when the perl interpreter is about to unload it, respectively.

Here's an example for a logging module that makes use of this facility:

# File :

package MyLog;

use strict;
use warnings;

    open MYLOG, ">", "mylog.txt";

sub log
    my $what = shift;

    # Strip the string of newline characters
    $what =~ s/\n//g;

    # The MYLOG filehandle is already open by virtue of the BEGIN
    # block.
    print MYLOG $what, "\n";



Written by Shlomi Fish