Sunday, January 18, 2009

A Perl template - Part I: The Basics

The hardest thing when it comes to programming is to sit in front of a blank screen and wonder how to start coding.
Good programming practices tell you to design your application before you type the first line of code.
Some program methodologies (Extreme Programming for example) will have you create the tests before you work on your main project.

For now, I am just going to present the very basics of Perl. The goal of the next few posts will be to build a very simple script skeleton. This template will serve as a base for a new project (and eliminate the dreaded white screen).

Enough talking, here is our first Perl program:

Type the above line in Notepadd++ and save the file as skeleton.pl.
The .pl extension means that the file is a Perl script.
Then open a DOS shell (cmd.exe) and type

C:\Perl\usr>skeleton.pl
This is easy
C:\Perl\usr>

The .pl file is executed by the C:\strawberry\perl\bin interpreter (if its correct location is in your PATH environment variable. Check how to see that here).
The print command displays a line on the standard output which is the DOS shell on your computer screen by default.

This program would run on Windows only. For Linux machines, you have to tell the computer where to find the Perl interpreter. Because we want our scripts to run on any machine (portability), we'll rewrite our first example with a few additions:

The first line starts with what is called a she-bang: #!
On Unix systems, it tells the operating system what the type of the file is and where to find the interpreter.
use warnings;
This line tells the Perl interpreter to give warnings for bad practices.

All lines starting with a # are comments.

The semi-column (;) at the end of non-comment lines are used to separate Perl statements. This is why the last ; can be omitted (but it is better to keep it in case you add more lines to the bottom of your file later).

The __END__ token tells the Perl parser to consider this line as the end of the program. Anything you write after it will not be considered a part of the Perl program and ignored.
You can use this knowledge to add some documentation at the bottom of your file.

French expression of the day:
"C'est le premier pas qui compte": The first step is always the hardest.

Next posts:
  • Perl development tools - Part II: setting up Notepad++
  • Our first Perl program - Part II: parsing the Perl command line
  • More about CPAN
  • Our first Perl program - Part III: Add a GUI interface
  • How to install Google Analytics on your Blogger blog
  • First version of FileInfo script

2 comments :

  1. Damien, It's worked! Yey! Many thanks for your blog. - simon.

    ReplyDelete
  2. "The .pl file is executed by the C:\strawberry\perl\bin interpreter (if its correct location is in your PATH environment variable. Check how to see that here)."

    Is there a link to verifying the location is in your PATH environment?

    ReplyDelete