use strict forces you to provide scoping information about
your variables. Hence:
use strict;
$global = 1;
will generate compile time errors because we haven't told
Perl about the scope of the $global variable.
Now there are several ways we can declare variables in Perl,
and of course they mean different things.
use vars, and our give globals:
# globals to our package.
use vars qw/$global1 $global2 $fred/;
our ($global1, $global2, $fred);
These can then be used anywhere in their package as you'd
expect of globals. They can also be accessed outside of the
package by fully qualifying them. eg
use strict;
package Fred;
our $name = "John";
package Main;
my $name = "Fred";
print $Fred::name; # prints "John";
print $name; # prints "Fred";
fully qualifying variables gives globals.
Kinda like the above, and your example.
use strict;
$::database = "backup"; # global variable in Main
# package.
package Fred;
print $::database; # prints "backup";
In your code you're created a new namespace (global) and
using that for your globals. Yes, it is ugly, but it's
perfectly valid.
my localizes variables to their block.
#!/usr/local/bin/perl -w
use strict;
my $fred = 3; # accessible from here to end
# of file/package.
{
my $fred = 2; # overrides previous $fred until
# end of block
print $fred; # prints "2";
}
print $fred; # prints "3"
local temporarily displaces the value of a variable
until the end of the block
use strict;
my @array = qw/this is a sentence/;
{
local $, = " "; # changes $, to " ". Using
# "my" with a Perl special
# variable generates a compile
# time error.
print @array; # prints "this is a sentence"
}
print @array; # prints "thisisasentence"
Be careful of declaring a local variable of the same
name as a another variable previously declared with my
in the same scope. It should complain, and it
does. That is:
use strict;
my $foo = "bar";
local $foo = 2; # will break.
# although
{
local $foo = 2; # will be fine.
}
The difference between my and local is a subtle one. Local
variables exist for that call stack, until the end of the
block. So if your block calls subroutines, the localised
variable will exist within those subroutines (and any
subroutines they call and any they call and so on - which
can cause nasty surprises).
Variables declared with my exist _only_ within their block.
This means that if the block calls a subroutine that is not
defined within the same block, then that subroutine does
not automatically get access to the variable (but you can
pass it in as an argument).
Excepting these, you cannot access variables declared within
a block, at all, from outside that block. That is:
use strict;
package Foo;
my $foo = 12;
package Bar;
print $Foo::foo; # this won't work
will result in a compile time error.
Phew! I hope that helps.
Jacinta.
|