Many programming languages require you to "pre-declare" variables -- that is, say that you're going to use them before you use them. Variables can either be declared as global (that is, they can be used anywhere in the program) or local (they can only be used in the same part of the program in which they were declared).
In Perl, it is not necessary to declare your variables before you begin. You can summon a variable into existence simply by using it, and it will be globally available to any routine in your program. If you're used to programming in C or any of a number of other languages, this may seem odd and even dangerous to you. This is, in fact, the case.
avoids accidental creation of unwanted variables when you make a typing error
avoids scoping problems, for instance when a subroutine uses a variable with the same name as a global variable
allows for warnings if values are assigned to variables and never used
takes a while to get used to, and may slow down development until it becomes instinctual
enforces a nasty, fascist style of coding which isn't nearly as much fun
Sometimes a little bit of fascism is a good thing, like when you want the trains to run on time. Because of this, Perl lets you turn strictness on if you want it, using something called the strict pragma. A pragma, in Perl-speak, is a set of rules for how your code is to be dealt with.
Other effects of the strict pragma are discussed on page 500 of the Camel.
In the interests of bug-free code and teaching better Perl style, we're going to use the strict pragma throughout this training course. Here's how it's invoked:
#!/usr/bin/perl -w use strict; |
That typically goes at the top of your program, just under your shebang line and introductory comments.
Once we use the strict pragma, we have to explicitly declare new variables using my. You'll see this in use below, and it will be discussed again later when we talk about blocks and subroutines.
Try running the program exercises/strictfail.pl and see what happens. What needs to be done to fix it? Try it and see if it works. By the way, get used to this error message - it's one of the most common Perl programming mistakes, though it's easily fixed.
There's more about use of my on page 189 of the Camel.