perlvariablesstrict

How to use `our` class variables with `UNITCHECK` correctly with `use strict`?


As Perl constants are somewhat strange to use, I decided to implement my "class variables" as our variables, just like:

our $foo = '...';

However when I added a UNITCHECK block using the class variables, I realized that the variables were not set yet, so I changed the code to:

BEGIN {
   our $foo = '...';
}

UNITCHECK {
    if ($foo eq 'bla') {
        #...
    }
}

Then I realized that I had mistyped some variable names in UNITCHECK, so I decided to add use warnings and use strict. Unfortunately I'm getting new errors like

Variable "$foo" is not imported at .. line ..

When I initialize the variable outside BEGIN, then the error is away, but then I have the original problem back.

So I wonder: Is our $var = 'value'; the remommended and correct use, or should it be split in our $var; outside the BEGIN and $var = 'value; inside BEGIN?

As my list of variables is rather long, I'm trying to avoid list them twice (introducing the possibility of misspelling some again).

What is the recommended correct way to do it?


Solution

  • our is lexically scoped so in your code the variable only exists in the BEGIN block. You will need to separate out the declaration from the assignment like this:

    our $foo;
    BEGIN {
        $foo = '...';
    }
    
    UNITCHECK {
        if ($foo eq 'bla') {
            #...
        }
    }