Search iEntry News



Formatting Your Perl Code

By Rodney Sellers
Expert Author
Article Date: 2009-11-24

I have worked with many programmers working with many different languages, so I am used to seeing code formatted different ways. The problem I run into and more often than I should, is when someone has a long program written to the left margin or improper formatting.

Once in college I ran into a program that started out left margin, then switched to single space indent then to tab indent at the end. I am still not sure it was all written by different people or if the guy just wrote it that way. My personal preference is tab indenting. It allows you to see what is in a loop and what is not very easily. Here is a very simple version of how I indent.

While ($number != 4)
{
print "inside loop\n";
$number++;
}

There are many variations on this format from double space indents to putting the { on the same line with the while loop.

While ($number != 4){
print "inside loop\n";
$number++;
}

To me, the first is easier to read if you have a large number of nested loops but it can get very large very quickly.

In college, I had a database professor that had a format style that I still have a lot of trouble reading. It is when you indent only the fist line of a loop.

While ($number != 4) {
print "inside loop\n";
$number++;
}

When you have a large number of loops nested together it can get very confusing, but by the end of the semester, I was able to read it... kind of.

My least favorite format style is when you indent the second line of the loop and nothing else.

While ($number != 4) {
print "inside loop\n";
$number++;
}

This format was the favorite of many of my professors in electoral engineering classes. I asked one of my professors once and he said it was easier to look at FORTRAN code that way.

Here are 4 different types of formatting your code. To make it easier for yourself or others to maintain, the code is to pick a format style and stick with it. If you are modifying someone else's code, try to stick with their style. It makes the code flow better and easier to understand.

About the Author:
Rodney Is A Staff Writter for iEntry.




Newsletter Archive | Article Archive | Submit Article | Advertising Information | About Us | Contact

PerlProNews is an iEntry, Inc. ® publication - 1998-2009 All Rights Reserved Privacy Policy and Legal