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

I have a module that provides some global variables and a few common subs. Some of the variables are set to default values. I presume I can assume that the values will be set before any code that uses the module can call any of the subs in the module. Is that a safe assumption if there are no BEGIN blocks involved? Example:

use strict; use warnings; package noname; require Exporter; our @ISA = ('Exporter'); our @EXPORT = qw($globalVariable UseVariable); my $globalVariable = 'Default value'; sub UseVariable { print $globalVariable; } 1; package main; noname::UseVariable ();

Prints:

Default value

If package main is in another file can this code bite me ($globalVariable used before it is initialised)?


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re: Compile order sanity check
by ikegami (Patriarch) on May 30, 2006 at 07:00 UTC

    use and require execute all of the top level code of the module before returning (unless this has already been done by an earlier use and require), so you are safe.

    Update: As pointed out by wsfp in chat, it's pointless to export $globalVariable. That exports the unused package variable $globalVariable rather than the lexical (my) variable $globalVariable. The simple fix would be to change
    my $globalVariable = ...;
    to
    our $globalVariable = ...;

Re: Compile order sanity check
by bobf (Monsignor) on May 30, 2006 at 05:17 UTC

    Based on my limited understanding of lexical variables, package variables, and the order of compilation...

    If package main is in another file, then you're going to have to use or require the file that contains package noname. Since $globalVariable was declared in noname with my it is a lexical variable, which isn't in the symbol table and isn't visible outside of the scope in which it was declared (i.e., you can't say $noname::globalVariable, as you could if it were declared with our). Therefore, IIUC the only way to access it from another module (package) is through Exporter (or an Exporter-like process), after the module that contains noname is used or required. If that's true then as long as you initialize the variable with your default value before the portion of the module that declares it and exports it returns (during compilation), you'll be OK.

    I hope a more knowledgeable monk will gently correct me if I'm wrong. :-)