in reply to a simple exercise in readability
I'd rewrite as follows:
#!/usr/bin/perl -l use strict; use warnings; use Getopt::Std; our ($opt_s); getopts('s'); # get the range boundaries my $range_start = ( $opt_s ) ? $ARGV[0] : $ARGV[0] + 1; my $range_end = $ARGV[1]; # compute the sum of the range my $range_length = $range_end - $range_start + 1; my $range_sum = ($range_start + $range_end) * $range_length / 2; print $range_sum;
The named variables make it easier to tell what it's doing. I might also consider handling the -s option like this:
my $range_start = $ARGV[0]; $range_start++ if ( $opt_s );
It's a little cleaner, but I think the ternary is actually clearer here. It's more obvious that there's a decision, and what it means.
Ordinarily I'd say it should have comments too, but I'm so enamored with the readability of my own code, I think it doesn't need them anymore. If there were more options, they'd definitely need documentation.
For bonus points, tell me how you might modify the program for usability purposes. For instance, how (if at all) would you handle improper input such as non-integer arguments (e.g. floating point numbers like 2.7)?
I'd probably just put in a check early on and die with a usage statement:
if ( $ARGV[0] !~ m{ \A [+-]? \d+ \z }xms || $ARGV[1] !~ m{ \A [+-]? \d+ \z }xms ) { die "usage: $0 [-s] <integer> <integer>\n"; }
A longer, more detailed usage message would be better, but you get the idea.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: a simple exercise in readability
by apotheon (Deacon) on Jan 15, 2007 at 15:07 UTC | |
by kyle (Abbot) on Jan 15, 2007 at 16:59 UTC |