Here's a version incorporating your approach, but in a way that's slightly more idiomatically "mine":
#!/usr/bin/perl -l use strict; use warnings; use Getopt::Std; our $VERSION = '1.0'; $Getopt::Std::STANDARD_HELP_VERSION = 'true'; my $help = ' syntax: series [-s] <first integer> <second integer> --help prints this help text and exits: invoking the help argument causes all other arguments to be discarded by this utility -s takes no arguments: changes program behavior so that the first number specified is the first number of the range, and not the number preceding it (syntax: series a+1 n) -- this option must precede all numerical arguments to the series utility description: This utility takes two integers as arguments and produces the sum of the range of integers starting after the first argument and ending with the second argument. '; our ($opt_s); getopts('s'); HELP_MESSAGE() and exit unless $ARGV[1]; foreach (@ARGV) { HELP_MESSAGE() and exit unless /^-?\d+$/ } my $start = shift @ARGV; my $end = shift @ARGV; if ($opt_s) { print( ($end - $start + 1) * ($start + $end) / 2 ) } else { print( ($end - $start) * ($start + $end + 1) / 2 ) } sub HELP_MESSAGE { print $help; }
I figured I might separate the help text dump for too few numerical arguments from the variable assignments to improve maintainability a tad. I also decided to use the Getopt::Std built in help and version output functionality. Thoughts . . . ?
edit: johngg pointed out the "unless" bug above, where unless @ARGV should read unless defined @ARGV instead.
|
- apotheon
CopyWrite Chad Perrin |
In reply to Re^2: a simple exercise in readability
by apotheon
in thread a simple exercise in readability
by apotheon
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |