I use two approaches for this.

Either, a module documents and exports an explicit initialization routine:

package Foo; my $dbh; sub init_foo { my( %script_config )= @_; # Read config file ... # Connect to database $dbh ||= $config{ dbh } || connect_to_foo_database( %script_config + ); # Set up cache ... };

Alternatively, I construct these things when they are first needed:

sub frobnicate { my( $self, %options )= @_; $options{ dbh } ||= $self->get_dbh; ... }; sub get_dbh { my( $self )= @_; $self->{ dbh } ||= do { DBI->connect( $self->{dbi_parameters} ); }; };

The approach is more explicit in the sense that things fail early, but it needs the explicit call by the person writing the script.

The other approach is more implicit in the sense that things only get initialized once they are needed.

I don't like the implicit magic of having a special name for the module which is called to configure things.

If I had to implement such magic, I would have something like this:

package Module::MagicInit; use strict; my @init_queue; sub register_init { push @init_queue, [ (caller(1))[2], @_ ]; }; sub init { for my $task (@init_queue) { my( $package, $callback, @args )= @$task; $callback->( @args ) or die "Init failed for $package."; }; };

... and then use that like so:

package Foo; use Module::MagicInit; register_init( \&my_init, 'Hello', 'World' ); sub my_init { my( $greeting, $name )= @_; print "$greeting, $name\n"; }; 1;
#!perl -w use strict; use Module::MagicInit; ... Module::MagicInit::init();

In reply to Re: Module for executing postponed initialization code by Corion
in thread Module for executing postponed initialization code by Dallaylaen

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.