use strict; #<--****
use warnings; #<---***
Declaring global variables using fully qualified names:
$main::x = 10;
print $main::x, "\n"; #10
Above okay under use strict.
Declaring global variables with use vars:
use vars qw{$x};
print $x, "\n"; #10
'use vars' provides a shortcut: you don't need to use the fully qualified variable name, which is what use strict requires.
Declaring global variables with our:
# $y = 'hello'; #error under use strict
our $y = 'hello';
print $y, "\n"; #hello
Once again, our provides a shortcut to having to
use fully qualified names under use strict.
What's the difference between our and use vars?
{
our $z = 5;
print $z, "\n"; #5
}
# print $z, "\n"; #error
print $main::z, "\n"; #5
{
use vars qw{$s};
$s = 'bye';
print $s, "\n"; #bye
}
print $s, "\n"; #bye
'use vars' has file scope, i.e. it applies to the whole file, and cannot be undone (e.g. with 'no use vars')--while our has block scope, so the short form of the variable name only works within the same block as the our statement.
Note that the global variable always exists no matter what method you use--the issue is whether you can refer to the global variable using the short form of the variable name or not. |