strict and -w

Because you don't have to predeclare variables in Perl, there is a big problem with typos:


$value = 42;
print "Value is OK\n" if $valu < 100; # UH OH


The -w Switch Will Warn of Uninitialized Variables


#!/usr/bin/perl -w  

$value = 42;
print "Value is OK\n" if $valu < 100; # UH OH

% perl uninit.pl
Name "main::valu" used only once: possible typo at uninit.pl line 4.
Name "main::value" used only once: possible typo at uninit.pl line 3.
Use of uninitialized value in numeric gt (>) at uninit.pl line 4.

"use strict"

The "use strict" pragma forces you to predeclare all variables using "my":

#!/usr/bin/perl -w  

use strict;
$value = 42;
print "Value is OK\n" if $valu < 100; # UH OH

% perl uninit.pl
Global symbol "$value" requires explicit package name at uninit.pl line 4.
Global symbol "$valu" requires explicit package name at uninit.pl line 5.
Execution of uninit.pl aborted due to compilation errors.

#!/usr/bin/perl -w  

use strict;
$value = 42;
print "Value is OK\n" if $value < 100;

% perl uninit.pl
Global symbol "$value" requires explicit package name at uninit.pl line 4.
Execution of uninit.pl aborted due to compilation errors.


#!/usr/bin/perl -w  

use strict;
my $value = 42;
print "Value is OK\n" if $value < 100;

% perl uninit.pl
Value is OK

Using my

You can use "my" on a single variable, or on a list of variables:

my $value = 42;
my $a;
my ($c,$d,$e,$f);
my ($first,$second) = (1,2);

<< Previous
Contents >> Next >>

Lincoln D. Stein, lstein@cshl.org
Cold Spring Harbor Laboratory
Last modified: Wed Oct 11 20:27:02 EDT 2000