One of the things I like about Perl is that you don't need to predeclare your variables like you do in C and C++. It's cleaner to predeclare, but it's often too much trouble. I usually am in a rush to code and want to just make up the variable name as I need it. In Perl (and Python, BTW), it is very convenient to do this. You just start using the variable and it works. This also applies to arbitrary types. You just start using arrays of arrays of hashes or whatever, and it just works and everyone's happy.
So why do I call this a trap? Well, with great power comes great responsibility. Since any variable name is valid, then typos are valid as well. It is not to hard to imagine something like:
# There is a bug here
@actionsList = ();
while (scalar(@ARGV)>0) {
my $arg = shift @ARGV;
if ($arg eq '-actions') {
my $action = shift @ARGV;
push @actionList, $action;
} else {
push @fileList, $arg;
}
}
#########################################
if (scalar(@actionsList)>0) {
foreach my $action (@actionsList) {
system $action;
}
}
and this has happenned to me many times. Anyway, the bug above (you've
probably aready spotted it) is that we're dealing with the array
@actionsList(plural) and inside the while, we
push onto @actionList(singular). The result of this is that
we'll be creating @actionList, but @actionsList
remains empty. So when it comes time for the if at the bottom, the system
calls never get executed.
Personally, I just live with it. But there are a couple ways to help you catch these:
-w flag. This turns on warnings,
but it generally catches more than I want, and I don't use it
personally.
use strict, which will force you to predeclare
your variables. You should also get acquainted with use
vars to help you predeclare your variables.
# There is a bug here
use strict;
use vars qw(@actionsList @fileList);
@actionsList = ();
while (scalar(@ARGV)>0) {
my $arg = shift @ARGV;
if ($arg eq '-actions') {
my $action = shift @ARGV;
push @actionList, $action;
} else {
push @fileList, $arg;
}
}
#########################################
if (scalar(@actionsList)>0) {
foreach my $action (@actionsList) {
system $action;
}
}
If you try to run that, it will actually complain about using
@actionList without defining it.
Again, I just live with it. Using use strict just
defeats the point of the convenience of using variables as I need them in
Perl.