G'day frank1,

In the "release notes for Perl 5.32.0", you'll see the introduction of "Chained comparisons capability". If you have that version, you can do this:

$ perl -E ' my @nums = qw{-1 0 1 9 10 11 19 20 21 23 49 50 51 55}; for my $in (@nums) { my $out; if ($in < 10) { $out = $in; } elsif (10 <= $in < 20) { $out = $in - 2; } elsif (20 <= $in < 50) { $out = $in - 3; } else { $out = $in - 4; } printf "IN: %2d OUT: %2d\n", $in, $out; } ' IN: -1 OUT: -1 IN: 0 OUT: 0 IN: 1 OUT: 1 IN: 9 OUT: 9 IN: 10 OUT: 8 IN: 11 OUT: 9 IN: 19 OUT: 17 IN: 20 OUT: 17 IN: 21 OUT: 18 IN: 23 OUT: 20 IN: 49 OUT: 46 IN: 50 OUT: 46 IN: 51 OUT: 47 IN: 55 OUT: 51

I've been using that new feature quite a lot. I believe it makes the definition of ranges, such as are in use here, much clearer and easier to read.

Note all the numbers that I've used for testing. This checks for edge cases around zero and the numbers where conditions change (as well as your two arbitrary numbers 23 & 55). This helps to highlight mistakes, as off-by-one errors are common when using <, <=, >= and >: you should aim to test like this regardless of whatever language or version you might be using.

Your written description only mentions "3 should be subtracted"; however, your code has instances where 2, 3 or 4 are subtracted. I'll leave you to make adjustments depending on what you really want.

— Ken


In reply to Re: subtracting numbers by kcott
in thread subtracting numbers by frank1

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.