Lexical variables are tagged with my
.
Their scope is limited to the surrounding statement block.
Global variables are introduced with our
, example:
our $x = 1; if( $x > 0) { my $x = 2; print " x = $x\n"; # prints 'x = 2' } print " x = $x\n"; # prints 'x = 1'
In early Perl versions the our
verb was not
available. Instead one had to write:
use vars qw( $x); $x = 1;
Global variables are global to a package. If the package
is not explicitly defined, a global variable is created in main::
.
Global variables can be made local
to a block. Their
value is saved and restored at the end of the block.
The new value becomes available not only inside the block but
also for all subroutines that are called from inside the block.
our $x = 1; f1(); f2(); # prints '1' sub f1 { local( $x) = 2; f2(); # prints '2' } sub f2 { print "x = $x\n"; }
The function local
is especially useful for temporarily changing
builtin variables. See section 7.7 for an example.
It shows
how STDOUT
is re-assigned to point to a text widget.