X hits on this document

PDF document

Running and Debugging Perl - page 19 / 30





19 / 30

Running and Debugging Perl

If we now pass the -h option, it's not treated as a filename, but rather as a request for help:

>perl –s nl3.plx -h nl3.plx Number lines in a file

Usage : nl3.plx [-h|-v] [filename filename...]

This utility prints out each line in a file to standard output, with line numbers added. >

If you're fortunate enough to be using an operating system that allows you to use Perl programs as executables, the shebang line will take care of specifying the –s switch, so you won't need to repeat it on the command line. So while this will work fine on UNIX:

>nl3.plx -v nl3.plx - line numberer, version 3

you'll probably need to say this on Windows:

>perl –s nl3.plx –v nl3.plx - line numberer, version 3

How It Works

The -s on the shebang or command line tells perl that any switches following the name of the Perl program will cause a Perl variable of the same name to be defined. For instance, this command line:

>perl -s something -v -abc

will set the variables $v and $abc. We therefore need to be ready to receive these variables, otherwise we will fall foul of use strict, so we put:

our ($v,$h);

If the variable is defined, we do something with it:

if (defined $v) { print "$0 - line numberer, version 3\n"; exit;


The special variable $0 contains the name of the program currently being run. It's good form to put this in any informational messages you produce about the program.

While -s is handy for quick tasks, there are two things that make it unsuitable for use in big programs:

You have no control over what switches should be recognized. Perl will set any variable, regardless of whether you want it to or not. If you're not actually using that switch, this will generate warnings. For instance:

>perl -s nl3.plx -v -foobar Name "main::foobar" used only once: possible typo. nl3.plx - line numberer, version 3 >

-abc is treated as one switch and sets $abc, rather than the three switches -a, -b, and -c.


Document info
Document views109
Page views109
Page last viewedFri Jan 20 06:37:33 UTC 2017