bschmer has asked for the wisdom of the Perl Monks concerning the following question:
Since the module is an object, the preferred style of my coworker was:use Module; BEGIN { $Module::variable = 1; };
Neither of us is horribly thrilled with the BEGIN block and would rather have something like:use Module; BEGIN { my $m = new Module; $m->setConfigVariable(); };
I've been poking around for modules that do something similar, but haven't come across anything. I've coded up a generic solution that mostly works using import but the variable gets reset on exiting import if I don't reference the real variable in import.use Module qw(-SetConfigVariable);
my $MyConfigVar=0; sub import { # Import gets called with a package and a list of items # We want to pick off the ones that start with - and # handle. Other cases need to be handled as they are # encountered my $package = shift; $Trace = new TracePkg unless defined($Trace); $Trace->entry(); my @params = @_; foreach my $item (@params){ if ($item =~ s/^-//){ my $varname = $item; $varname =~ s/^no_//i; my $oldvalue = eval "\$$varname"; if ($item =~ /^no_/i){ eval "\$$varname = 0"; } else { eval "\$$varname = 1"; } my $newvalue = eval "\$$varname"; $Trace->comment(msg => "Handled param $varname. Changed from $o +ldvalue to $newvalue."); } else { $Trace->warn(msg => "Did not handle param $item"); } } # I haven't figured out why we need this statement but commenting it + out will cause # the variable to get reset. $Trace->trace(msg => "Var=$MyConfigVar"); $Trace->exit(); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Set attribute on a module
by dragonchild (Archbishop) on Apr 14, 2006 at 18:25 UTC |