简体   繁体   中英

Initializing global variable on Perl module (with BEGIN block) include

I'm trying to initialize a global variable from a Perl module that has a BEGIN block, but I can't manage to get it work.

This is the Perl module

Package A::B;
our $var;

BEGIN{
  $var ||= "/some/default/path";

  #create/access files/folders in $var
}

This is my CGI script

use A::B;
$A::B::var = "/correct/path";

But #error returned because $var is not the correct path

The BEGIN block is being executed before the correct path is assigned to $var . Is there a way to work around this without having to remove code from the BEGIN block?

BEGIN { $A::B::var = "/correct/path" }
use A::B;

This answer is unsatisfying to me, but I can't think of any other way, given how your A::B is designed. Ideally a module doesn't depend on who is using it or how often, but this module can really only be used once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM