Electric Type

Multimedia

About Us

News

Help

Intro to Perl for CGI

Page 2 — The Rules of the Road

What do you need to know? It's simple. Just follow these basic rules.

Rule #1: Always put this line at the top of your Perl script, no excuses:

#!/usr/local/bin/perl
It tells the server running your script that what follows isn't Russian on acid but Perl. The server likes Perl, it just needs to know what it is. So don't forget to start with this line. Otherwise you'll spend hours trying to find what's wrong with your syntactically correct script only to discover that you left out the most basic thing.

Rule #2: Always put a semicolon at the end of every line. If you don't, you'll never, ever, ever get a script to work. So just do it.

Rule #3: Put comments everywhere you can. What are comments? Comments are complete sentences that describe what the script does at a certain point. Any line beginning with a "#" mark is a comment line, with the exception of the line in Rule #1. Look at the example below to see how comments might be useful.


# In the following code, I'm going to create a variable that contains 

# the info that will go into a log. But I'm going to keep the

#  formatting really simple so it'll be displayed in

# an easy-to-read fashion.



my $in{'logdata'} = <<END;

$in{'name'}

$in{'formelement1'}   |   $in{'radiobutton2'}

$in{'checkbox1'}        |   $in{'checkbox2'}

END



As the author of this script, you probably know the purpose of that variable, but what if someone else had to work with the script? You wouldn't want them to spend the rest of their lives deciphering your uncommented code (unless they're being paid by the hour). So try to make it easy on everyone else.

Rule #4: Clean code is maintainable code. Writing clean code falls under the good citizen laws, as does Rule #3. Just because you could write something like this:

for ($i=0;$i<=$#blah;$i++){if ($blah[$i]~=/punk boy/g;)
{print "I hate this code";}else { print "nappy";}}
... doesn't mean you should. It may not create any errors, but it's difficult to read, not to mention just plain ugly. Even with comments, it would take a person days to figure out that this is nothing more than a "for" loop, running through the "blah" array, looking for the phrase "punk boy." If the phrase exists, it prints "I hate this code"; if it doesn't, it prints "nappy." It's a lot prettier and easier to understand if you do it like this:

for ($i = 0; $i <= $#blah; $i++) {

	if ($blah[$i] ~= /punk boy/g;) {

		print "I hate this code";

	}else {

		print "nappy";

	}

}

All clear? Don't worry, Grasshoppper; you'll get it.

next page»


Dynamic HTML  

Frames  

HTML Basics  

Stylesheets  

Tables  

XML  

Javascript  

Database Connections  

Intro To Perl  

HTML 4.0  

Valid HTML 4.01!
Valid CSS!

Breadcrumb

© ElectricType
Maintained by My-Hosts.com
Site map | Copyright | Disclaimer
Privacy policy | Acceptable Use Policy
Legal information.