in reply to "Correct" program style questions
I've just gone through about 300 CGI scripts helping people clean up code and convert to Apache::Registry. Here's some of what I've learned.
-
Beginners need structure more than anything. I like your code for parameters because it is easy to add a new one correctly. We had serious problems with tainting and your code should eliminate that.
The only thing I would change with your param code is to reformat it like this:
That's easier to cut and paste. Beginners always cut and paste regardless of how many times I warn them it's a bad habit. "Use loops!" "Use subroutines!" "Sigh." "Ok, but at least fix the indentation."my $_name = param('name') || ''; my ( $name ) = $_name =~ /^([[:alpha:][:punct:][:space:]]+)$/; my $_color = param('color') || ''; my ( $color ) = $_color =~ /^([[:alpha:]]+)$/; -
We had major problems with duplicated constants (between and within scripts). I recommend creating an application-setup module and then importing it into every script. Once again, beginners will look for how it was done before and then try to copy it. Something simple like this:
The repeated use of the package name is ugly, but it cuts and pastes more easily. People will also automatically use the full package name in the CGI code, so confusion with lexical variables is reduced.package MyApp; use strict; $MyApp::data_dir = "/usr/local/data"; $MyApp::db_user = "app"; $MyApp::db_password = "secret"; ... 1; -
Put a few utility subroutines in the application-setup module, just so that people will see how that works. For example, create a sub that untaints a parameter used in many different scripts. The people I worked with had trouble thinking ahead -- they never made decisions that reduced maintenance work -- but they did recognize things that were easier "now".
-
If you think you might use mod_perl some day, wrap all your scripts in a sub and then call the sub. Like this:
The sub must be removed when you convert to mod_perl, but it will prevent subtle problems and it will get people thinking of the CGI script in terms of a "request handler" instead of "running a script".#!perl handler(CGI->new); sub handler { my($q) = @_; ... }
|
---|