2

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?

U. Windl
  • 3,480
  • 26
  • 54
  • See also [an example](https://stackoverflow.com/a/71779113/4653379) for most of what is asked, including libraries for constants in Perl, like `Const::Fast` and `Readonly` (on [this page](https://stackoverflow.com/a/71804896/4653379) as well) – zdim Apr 11 '22 at 17:30

1 Answers1

5

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') {
        #...
    }
}
brian d foy
  • 129,424
  • 31
  • 207
  • 592
JGNI
  • 3,933
  • 11
  • 21
  • 2
    Note that `my` would work just as well here and should therefore be used instead of `our`. There's almost no reason to ever use `our`. A notable exception is Exporter's vars. – ikegami Apr 08 '22 at 13:19
  • Well the code is part of a package, so I guess `my` won't do for class/package-level "constants" (that's what the `our` variable actually are). Also, as the list of such variables is rather long, it makes the "structure" of the code rather ugly (having to declare the long list, but not being able to initialize, and the initialize that list of variables). – U. Windl Apr 11 '22 at 07:23