You are on page 1of 1

Strict vars

Perl is generally trusting about variables. It will alllow you to create them out of thin air, and that's what we've been doing in our programs so far. One way to make your programs more correct is to use strict vars, which means that you must always declare variables before you use them. You declare variables by using the my keyword, either when you assign values to them or before you first mention them:
my ($i, $j, @locations); my $filename = "./logfile.txt"; $i = 5;

This use of my doesn't interfere with using it elsewhere, like in subs, and remember that a my variable in a sub will be used instead of the one from the rest of your program:
my ($i, $j, @locations); # ... stuff skipped ... sub fix { my ($q, $i) = @_; # This doesn't interfere with the program $i! }

If you end up using a variable without declaring it, you'll see an error before your program runs:
use strict; $i = 5; print "The value is $i.\n";

When you try to run this program, you see an error message similar to Global symbol ``$i'' requires explicit package name at a6-my.pl line 3. You fix this by declaring $i in your program:
use strict; my $i = 5; # Or "my ($i); $i = 5;", if you prefer... print "The value is $i.\n";

Keep in mind that some of what strict vars does will overlap with the -w flag, but not all of it. Using the two together makes it much more difficult, but not impossible, to use an incorrect variable name. For example, strict vars won't catch it if you accidentally use the wrong variable:
my ($i, $ii) = (1, 2); print 'The value of $ii is ', $i, "\n";

This code has a bug, but neither strict vars nor the -w flag will catch it.

You might also like