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.


In reply to Re: a simple exercise in readability by kyle
in thread a simple exercise in readability by apotheon

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.