Hi apotheon,

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.


s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/

In reply to Re: a simple exercise in readability by liverpole
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.