in reply to a simple exercise in readability
I'm a fan of producing a syntax message whenever arguments to a program are expected. That way, the user never has to guess what the program does, nor what the program expects for input.
Additionally, if you don't check to see that you DID get input, then you'll end up getting errors or "harder to track" unexpected results.
That's why I'd suggest doing an assignment to your command line variables up front, and aborting with a syntax message if the program doesn't get what it wants. That has the additional benefit of letting you do validity checking on those variables next, as well as simplifying your code later.
Here's how I might "neaten it up" a bit:
#!/usr/bin/perl -l # Libraries use strict; use warnings; use Getopt::Std; use File::Basename; our ($opt_s); getopts('s'); # Globals my $iam = basename $0; my $syntax = " syntax: $iam <first number> <second number> Your syntax message here. "; # Command-line (my $x = shift) or die $syntax; (my $y = shift) or die $syntax; # Validity checking ($x =~ /^-?\d+$/) or die "$iam: value $x not an integer\n"; ($y =~ /^-?\d+$/) or die "$iam: value $y not an integer\n"; # Main program if ($opt_s) { printf "%d\n", ($y - $x + 1) * ($x + $y) / 2; } else { printf "%d\n", ($y - $x) * ($x + $y + 1) / 2; }
To my eye, the main program is a lot easier to read now, as a result of assigning to $x and $y. That's partly because the lines are a lot shorter, so each printf statement fits on its own, single line.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: a simple exercise in readability
by apotheon (Deacon) on Jan 15, 2007 at 14:33 UTC | |
by liverpole (Monsignor) on Jan 15, 2007 at 15:32 UTC | |
by apotheon (Deacon) on Jan 15, 2007 at 15:40 UTC | |
by johngg (Canon) on Jan 15, 2007 at 16:57 UTC | |
by apotheon (Deacon) on Jan 15, 2007 at 17:08 UTC | |
by johngg (Canon) on Jan 15, 2007 at 14:51 UTC | |
by apotheon (Deacon) on Jan 15, 2007 at 14:55 UTC | |
by johngg (Canon) on Jan 15, 2007 at 15:55 UTC | |
|
Re^2: a simple exercise in readability
by kyle (Abbot) on Jan 15, 2007 at 17:38 UTC | |
by liverpole (Monsignor) on Jan 15, 2007 at 17:46 UTC |