Robert's Perl Tutorial
Consider for a moment this little program:
@input=@ARGV; $outfile='outfile.txt'; open OUT, ">$outfile" or die "Can't open $outfile for write:$!\n"; $input2++; $delay=2 if $input eq 'sleep'; sleep $delay; print "The first element of \@input is $input\n"; print OUY "Slept $delay!\n";
It doesn't do much. Just prints out the first argument supplied, and demonstrates the
sleep function. The program itself
is full of holes, and it is only a few lines. How many errors can you spot? Try and count
them. When you are finished, execute the program with error-checks enabled:
perl -w script.pl hello
Perl finds quite a few errors. The
-w switch finds, among other heinous sins:
$input2is used only once. It is a useless variable.
print OUYI'm trying to print to a non-existent filehandle. With
-wan alarm is raised, as it would be if I tried to write to a filehandle which was read-only.
$delayis uninitialised if 'sleep' is not the first parameter. Making variables spring into the air on demand is not good programming practice. They should be defined carefully first.
-w is a Good Thing. It forces
you to write cleaner code. So use it, but don't be afraid not to for very short programs.