Smarter scripts: Help!

  1. Capturing errors
  2. Smarter scripts
  3. Command-line switches

One of the advantages of subroutines is that partitioning off some Perl lines allows us to call those lines from multiple places without having to retype the lines. This improves the readability of our script and also the reliability. If we make a mistake in the subroutine, we can fix it in the subroutine.

We’ve got this subroutine called help but currently the only way to see it is to do something wrong. It might be nice to ask for the help without having to do something wrong.

When we want to alter the way a program works from the command line, we usually use switches. In Unix, switches usually begin with a single dash if they are a single character, or double dashes if they are a word. We’ll use words here just to make them easier to read. For example, to display the “help” message, we might use “./show –help”.

Add the following five lines above the “first item on the command line” comment:

#if they ask for help, do it and exit
if ($ARGV[0] eq "--help") {

Now, type:

./show --help

And you should see the help message displayed. It doesn’t matter what else you type on the command line, as long as the first argument is “--help” you’ll get the help message and that’s it.

The important new section is the one that checks $ARGV[0]. @ARGV is the list of all command-line arguments. In Perl, lists—often called arrays, or simple arrays—begin with the @ character. If, however, you want an item in the array, you preface it with the dollar sign.

$ARGV[0] is the first item in the list called ARGV. Perl, like many programming languages, starts counting from zero rather than from one. The first item in a list is item 0, not item 1. The second item is $ARGV[1] (if there is one), and so on.

What we’re checking is whether or not the first argument is equal to “--help”. If it is, we call the help subroutine and then exit. In Perl, exit will end the script completely. It doesn’t matter what else comes after the exit line, Perl ends the script and returns you to the command line.

Finally, don’t forget to add a line to the help text describing how to get help:

print "\t--help: print this help text\n"

You’ll always want to update your help subroutine whenever you add new features to your script, or modify existing features.

  1. Capturing errors
  2. Smarter scripts
  3. Command-line switches