Setting global variable value in Perl
I am having one perl module which sets values of some global variable to constant. I need to set the value of these global variables to a value which is available to me only when I call开发者_开发百科 the new() .
Is there any way I can achieve it ?
You use our
to declare a variable as global. You can then access it from other places in the same package if they also declare it as an our
variable in their lexical scope. From outside the package, you can only access it as with a package:: prefix.
Example:
package Foo;
use strict;
use warnings;
sub new {
our $bar = $_[1];
return bless {}, $_[0];
}
sub get_bar {
our $bar;
return $bar;
}
1;
In another file:
use strict;
use warnings;
use Foo;
my $foo = Foo->new('baz');
print "This is baz: ", $foo->get_bar, "\n";
print "So is this: ", $Foo::bar, "\n";
精彩评论