[sf-perl] Scope of a variable

Garth Webb garth.webb at gmail.com
Thu Mar 8 13:39:58 PST 2007


Unless your code is in the same package as the global, you need to give the
full package name to access global variables defined by our (also use vars):

$ cat Foo.pm
package Foo;

our $GLOBAL;

sub set_foo { $GLOBAL = 'foo' }
1;
$ cat Bar.pm
package Bar;

sub set_bar { $Foo::GLOBAL = 'bar' }
1;
$ cat test.pl
#!/usr/bin/perl -w

use strict;

use lib qw(./);

use Foo;
use Bar;

print "GLOBAL = $Foo::GLOBAL\n";

Foo->set_foo;
print "GLOBAL = $Foo::GLOBAL\n";

Bar->set_bar;
print "GLOBAL = $Foo::GLOBAL\n";
$ perl test.pl
Use of uninitialized value in concatenation (.) or string at test.pl line
10.
GLOBAL =
GLOBAL = foo
GLOBAL = bar

On 3/8/07, nheller at silcon.com <nheller at silcon.com> wrote:
>
>
> Following is a cut-down version of what I'm trying to do.
> The problem I'm having is that the variable, $intendedDest, is not holding
> its value from the called code (in Navigate.pl) to the calling code
> (Migrate.pl).
>
> Can somebody help?
>
>
> # ===== Migrate.pl =====
>
> #!Perl  -w
>
> use strict;
> use warnings;
>
> my $ccDir = $ARGV[0];
> my $currentLocation = "c:\\ADO_new";
> require $currentLocation . "\\Navigate.pl";
>
> our $intendedDest = 0;
>
> Nav_to_start::Navigate($ccDir);
>
>
>
>
> #  ===== Navigate.pl =====
>
> package Nav_to_start;
>
> use Fcntl ':mode';
>
> BEGIN { }
>
>     sub Navigate {
>             my $choiceResponse = <STDIN>;
>             chomp($choiceResponse);
>             $intendedDest = $choiceResponse;
>     }
>     return 1;
> END { }
>
>
>
>
>
>
>
> > nheller at silcon.com wrote:
> >> I'm trying to create a variable that is visible in multiple namespaces.
> >> I tried declaring the variable using "our".
> >> With use strict in effect, the code seems to treat the variable as a
> >> local
> >> in each place that it's used.  IOW, it doesn't hold value from one
> >> namespace to the next.
> >> Can anybody tell me where I'm going wrong?
> >
> > Can you show us the code which demonstrates what you're trying to
> > accomplish?
> > _______________________________________________
> > SanFrancisco-pm mailing list
> > SanFrancisco-pm at pm.org
> > http://mail.pm.org/mailman/listinfo/sanfrancisco-pm
> >
>
> _______________________________________________
> SanFrancisco-pm mailing list
> SanFrancisco-pm at pm.org
> http://mail.pm.org/mailman/listinfo/sanfrancisco-pm
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.pm.org/pipermail/sanfrancisco-pm/attachments/20070308/a4c598d1/attachment.html 


More information about the SanFrancisco-pm mailing list