3.1. "use strict", Luke!
Perl has a pragma (= an interpreter-related directive) known as use strict;
, which among other things, makes sure all the variables you use will be declared with my
. If you reference a variable that was not declared with my
it will generate an error.
Using use strict
is in most cases a good idea, because it minimises the number of errors because of typos. Just type use strict;
at the beginning of your program and you can sleep better at nights.
As an example, here is the primes program, use strict
-ed:
use strict; use warnings; my (@primes, $i); MAIN_LOOP: for( @primes=(2), $i=3 ; scalar(@primes) < 200 ; $i++ ) { foreach my $p (@primes) { if ($i % $p == 0) { next MAIN_LOOP; } } push @primes, $i; } print join(", " , @primes), "\n";
Notice the use of my
in the declaration of the foreach
loop. Such just-in-time declarations, inspired by C++, are possible in perl.