Anthony Ettinger wrote:
I want to double-check that it is correct to use "our" to import globals.
#!/usr/bin/perl -w
use strict;
BEGIN {
our $foo = 'foo';
}
sub something {
our $foo;
our $bar;
...at this point I can see 'foo' and 'bar' values.
}
END {
our $bar = 'bar';
}
[snip]
Variable "$foo" is not imported at ./script.pl line xx
Variable "$bar" is not imported at ./script.pl line yy
Global symbol "$foo" requires explicit package name at ./script.pl line xx.
Global symbol "$bar requires explicit package name at ./script.pl line yy.
Is this the correct way to import globals?
"import" here might better be "inherited". i.e., instead of "$foo is not
imported", it should say what it really means which is "I can't find any
$foo in this scope". Unless perl knows any better (e.g., with 'use
vars'), it assumed variables are scoped to the current block (e.g., with
'my').
'our' looks like it creates a globally scoped variable. However, what
'our' actually does is associate an unqualified name for a package
variable. E.g., if you use 'our $bar;' in the package 'Foo', then when
perl sees '$bar' it knows that you really mean '$Foo::bar'. But 'our'
only effects the current scope.
You were not trying to "import" any variables (e.g., from a different
file), but you were trying to access a package var using a name that no
longer existed. As always, however, the file is a block.
package main;
$main::foo = 'bar';
{
our $foo = 'blam'; # $main::foo eq 'blam'
$foo .= ' razz'; # $main::foo eq 'blam razz'
}
$foo = 'bar'; # $main::foo eq 'bar'
# With strict:
# Variable "$foo" is not important at ...
# Global symbol "$foo" requires explicit package name at ...
# Execution of ... aborted due to compilation errors.
my $foo = 'bah!'; # $main::foo eq 'bar' && $foo eq 'bah!'
So the answer is to always 'use strict', 'use warnings', use perldoc,
and make sure it works as documented.
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>