"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 myit will generate an error.

Using use strictis 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 myin the declaration of the foreachloop. Such just-in-time declarations, inspired by C++, are possible in perl.


Written by Shlomi Fish