Pages

Strict global and local variables

If you use the strict directive in your Perl code, and you should do that, you have to specify if a variable you are declaring is local (it is "my" variable) of global (it is "our" variable).

Local variables can't be referenced outside the current scope, and they are the preferred ones, if you want to keep your code reasonable readable.

#!/usr/bin/perl
use strict;
use warnings;

our $gRec = 99; # 1.
my $rec = 4; # 2.
print "Records ", $gRec, ' ', $rec, "\n";
{
my $rec = 88; # 3.
$gRec = 42;
print "Records ", $gRec, ' ', $rec, "\n";
}
print "Record ", $rec, "\n";

1. $gRec is a global variable.
2. $rec is a variable with local file scope.
3. we declare another $rec variable, limited to the current scope, that here hides the local file $rec defined in (2).

Beginning Perl by Simon Cozens is a good book to start with Perl. Scoping is discussed on chapter 2.

No comments:

Post a Comment