Приглашаем посетить
Кулинария (cook-lib.ru)

[Chapter 8] 8.7 File-Level my( ) Variables

PreviousChapter 8
Functions
Next
 

8.7 File-Level my( ) Variables

The my() operator can also be used at the outermost level of your program, outside of any subroutines or blocks. While this isn't really a "local" variable in the sense defined above, it's actually rather useful, especially when used in conjunction with a Perl pragma:[4]

 use strict;

[4] A pragma is a compiler directive. Other directives include those to set up integer arithmetic, overload numeric operators, or request more verbose warnings and error messages. These are documented in Chapter 7 of Programming Perl and the perlmodlib (1) manpage.

If you place this pragma at the beginning of your file, you will no longer be able to use variables (scalars, arrays, and hashes) until you have first "declared" them. And you declare them with my(), like so:

use strict;
my $a;                         # starts as undef
my @b = qw(fred barney betty); # give initial value
...
push @b, qw(wilma);            # cannot leave her out
@c = sort @b;                  # WILL NOT COMPILE

That last statement will be flagged at compile time as an error, because it referred to a variable that had not previously been declared with my (that is, @c). In other words, your program won't even start running unless every single variable being used has been declared.

The advantages of forcing variable declarations are twofold:

  1. Your programs will run slightly faster (variables created with my are accessed slightly faster than ordinary variables[5]).

    [5] In this case, "ordinary variable" is really a package variable (so $x is really $main::x). Variables created with my() are not found in any package.

  2. You'll catch mistakes in typing much faster, because you'll no longer be able to accidentally reference a nonexisting variable named $freed when you wanted $fred.

Because of this, many Perl programmers automatically begin every new Perl program with use strict.


PreviousHomeNext
8.6 Semiprivate Variables Using localBook Index8.8 Exercises