X hits on this document

PDF document

Running and Debugging Perl - page 18 / 30

71 views

0 shares

0 downloads

0 comments

18 / 30

Chapter 9

However, the kind of code we're likely to put on the command line doesn't really need this sort of strictness. It's still useful to have the -M switch to load modules – the CPAN modules LWP::Simple, Tk, and HTML::Parser have been used in the past to create a one-line graphical web browser!

  • -

    s

As well as passing switches to perl, you may want your program to have switches of its own. The -s switch (usually specified on the shebang line) tells perl to interpret all command line switches following the filename as variables (for example: $v, $h) and removed from @ARGV. This means that you can process these switches in any way you want.

For instance, a lot of programs will display a help message explaining their usage, when called with the

  • -

    h switch at the command line. Similarly, they'll give their version number if -v is used. Let's make

some of our own programs do this:

Try It Out : Reading Command Line Options

We're going to add 'help' and 'version number' messages to nl.plx, the line numbering program we wrote in the last chapter. Note that this example uses our and will therefore only work for Perl versions 5.6 and above:

#!/usr/bin/perl -s

  • #

    nl3.plx

use warnings; use strict;

my $lineno; my $current = ""; our ($v,$h);

if (defined $v) {

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

print <<EOF; $0 – Number lines in a file

Usage : $0 [-h|-v] [filename filename...]

This utility prints out each line in a file to standard output,

with line numbers added.

EOF

exit;

}

while (<>)

{

if ($current ne $ARGV) $current = $ARGV;

{

print "\n\t\tFile: $ARGV\n\n"; $lineno=1; } print $lineno++; print ": $_";

}

296

Document info
Document views71
Page views71
Page last viewedSat Dec 03 23:16:14 UTC 2016
Pages30
Paragraphs723
Words10014

Comments