As you know, when you use my , you create a local non-packet area. To create a package variable, use our , not my :
my $foo = "this is a locally scoped, non-package variable"; our $bar = "This is a package variable that visible in the entire package";
Even better:
{ my $foo = "This variable is only available in this block"; our $bar = "This variable is available in the whole package": } print "$foo\n";
If you do not put use strict in your program, all variables are defined as package variables. Therefore, when you do not install it, it works as it seems to you, and should prevent it from breaking your program.
However, as you can see in the following example, using our will solve your dilemma:
File Local/Foo.pm
#! /usr/local/bin perl package Local::Foo; use strict; use warnings; use feature qw(say); use Exporter 'import'; our @EXPORT = qw(testme); our $bar = "This is the package bar value!"; sub testme {
File test.pl
#! /usr/local/bin perl use strict; use warnings; use feature qw(say); use Local::Foo; my $foo = "This is foo"; our $bar = "This is bar"; testme; say ""; $Local::Foo::bar = "This is the NEW value for the package bar"; testme
And, output:
Use of uninitialized value $foo in concatenation (.) or string at Local/Foo.pm line 14. The value of $main::foo is "" The value of $main::bar is "This is bar" The value of $Local::Foo::bar is "This is the package bar value!" The value of bar is "This is the package bar value!" Use of uninitialized value $foo in concatenation (.) or string at Local/Foo.pm line 14. The value of $main::foo is "" The value of $main::bar is "This is bar" The value of $Local::Foo::bar is "This is the NEW value for the package bar" The value of bar is "This is the NEW value for the package bar"
The error message you receive is the result of $foo , which is a local variable, and therefore does not appear inside the package. Meanwhile, $bar is a package variable and is displayed.
Sometimes it can be a little tricky:
if ($bar -eq "one") { my $foo = 1; } else { my $foo = 2; } print "Foo = $foo\n";
This does not work because $foo contains only the value inside the if block. You must do this:
my $foo; if ($bar -eq "one") { $foo = 1; } else { $foo = 2; } print "Foo = $foo\n";
Yes, it may be a little to wrap your head around it first, but use use strict; and use warnings; is now exhaustive and for good reason. Using use strict; and use warnings; probably eliminated 90% of the mistakes people make in Perl. You cannot go wrong when setting the value of $foo in one part of the program and try to use $foo in another. This is one of the things that I really missed in Python.