Another Example

Here's a simple example (in Listing 15.3) that processes a file in various ways depending on the switches that you use with that script.

Listing 15.3. The switches.pl Script
1:  #!/usr/bin/perl -w
2:  use strict;
3:  use Getopt::Std;
4:  use vars qw($opt_r $opt_l $opt_s $opt_n);
5:
6:  if (! getopts('rlsn')) {
7:      die "Usage: switches.pl -rlsn
";
8:}
9:
10: my @file = <>;
11:
12:if ($opt_s) {
13:     @file = sort @file;
14: }
15:
16:if ($opt_n) {
17:     @file = sort {$a <=> $b}  @file;
18: }
19:
20:if ($opt_r) {
21:     @file = reverse @file;
22: }
23:
24: my $i = 1;
25: foreach my $line (@file) {
26:     if ($opt_l) {
27:         print "$i: $line";
28:         $i++;
29:     }  else {
30:         print $line;
31:     }
32: }
					

This script uses single switches only, with no values (note the call to getopts in line 7; there are no colons after any of those options. Those switches are -r, to reverse the contents of the file; -s, to sort the lines of the file; -n to sort the lines numerically; and -l to print line numbers. You can combine options on the command line, although some multiple options don't make sense (-sn sorts the file, and then resorts it numerically).

Line 4 predeclares our variables, so they won't suddenly spring into existence when getopts creates them (and cause use strict to complain).

The test in lines 6 through 8 make sure the script is being called with the right options. If a stray option slipped through (for example, an -a or -x), then the script exits with a usage message.

Finally, the various if statements test for the existence of the $opt_r, $opt_l, $opt_s, and $opt_n variables, and performs different operations depending on which options were called on the command line. Any arguments that aren't switches remain in @ARGV after getopts is done, and are read into the script via the <> operator in line 10.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset