DISCLAIMER: THESE PAGES ARE STILL UNDER CONSTRUCTION. NO CODE EXAMPLE BEEN TESTED YET.

Perl Traps

Typos are valid variable names too


[Next Page] Table of Contents: small | med | large

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:

The above code could be rewritten as:
	# 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.


© 2001 Steve Hwan, hostname: @pacbell.net, username: svhwan
You should probably use the word "PERL" in the subject line to get my attention.
Last Modified: Wed Apr 11 23:34:23 2001