"Perl for Perl Newbies" - Part 2Declaring Local Variables with "my""use strict", Luke!

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);

    @primes=(2), $i=3 ;
    scalar(@primes) < 200 ;
    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.

Written by Shlomi Fish