ady has asked for the wisdom of the Perl Monks concerning the following question:

Hi folks

I have a module where I load data from the __DATA__ section to a global DSTRUCT in a sub. The DSTRUCT is accessed by sub's @EXPORT'ed by the module. To call any of the 'accessor' subs, I have to call the 'load' sub first (once).

How do I assure that the 'load' sub is called 'automagically' before any 'accessor' sub', - preferably at the pt. when a program 'use's my module? A BEGIN block doesn't do the job.

Best regards,
allan dystrup

Replies are listed 'Best First'.
Re: Loading module data
by ikegami (Patriarch) on Apr 28, 2006 at 06:24 UTC

    DATA is not set until the file is fully compiled. Change
    BEGIN { load(); }
    to just
    load();

    Whatever code is at the top level of the .pm or in BEGIN blocks will get executed before use or require returns, so it's still done "at the pt. when a program 'use's my module". Also, it will only get executed the first time use or require is called in a given interpreter, so it's safe to use the module from multiple files. For example:

    # mod.pm package mod; sub load { print(<DATA>); print("loaded\n"); } load(); 1; __DATA__ some data
    # script.pl BEGIN { print("Before 'use mod;'\n"); } use mod; BEGIN { print("After 'use mod;'\n"); } use mod;

    output:

    Before 'use mod;' some data loaded After 'use mod;'

    Updated

      You're right ikegami,
      Just putting a load(); in the module is the cleanest way to do the job.
      Thanks!
      allan

      PS:
      I was trying load(); in a BEGIN block in the module, -- that didn't work, and now I see why.
Re: Loading module data
by davido (Cardinal) on Apr 28, 2006 at 06:33 UTC

    One reason a BEGIN block "doesn't do the job" (probably among several reasons) is described in perldata:

    Note that you cannot read from the DATA filehandle in a BEGIN block: the BEGIN block is executed as soon as it is seen (during compilation), at which point the corresponding __DATA__ (or __END__) token has not yet been seen.

    In SelfLoader, you can read about how to use the DATA filehandle in packages other than package main.


    Dave

Re: Loading module data
by Corion (Patriarch) on Apr 28, 2006 at 06:22 UTC

    Without seeing your code, I think you're trying to solve the wrong problem. At load time, all bare code within a module is run and you don't even need a BEGIN block. My guess is that your __DATA__ section and your module get mixed up. The DATA filehandle belongs to the __DATA__ section of the main program. If you want to read the __DATA__ section of your module, you need to use My::Module::DATA.

      to Corion ...
      Yes indeed, it was an X/Y question, -- no need for BEGIN here. Thanks -- allan
      Is there no way to have a module read "its own" __DATA__ section at 'use time' ?

      Here's the code: allan