in reply to declare globally
will generate compile time errors because we haven't told Perl about the scope of the $global variable.use strict; $global = 1;
Now there are several ways we can declare variables in Perl, and of course they mean different things.
use vars, and our give globals:
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# globals to our package. use vars qw/$global1 $global2 $fred/; our ($global1, $global2, $fred);
fully qualifying variables gives globals.use strict; package Fred; our $name = "John"; package Main; my $name = "Fred"; print $Fred::name; # prints "John"; print $name; # prints "Fred";
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.use strict; $::database = "backup"; # global variable in Main # package. package Fred; print $::database; # prints "backup";
my localizes variables to their block.
local temporarily displaces the value of a variable until the end of the 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"
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 @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"
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:
will result in a compile time error.use strict; package Foo; my $foo = 12; package Bar; print $Foo::foo; # this won't work
Phew! I hope that helps.
Jacinta.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Globals, localisation and strict.
by Juerd (Abbot) on Jan 09, 2002 at 06:21 UTC |