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\n";
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 ...

Get Sams Teach Yourself Perl in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.