... "If the number is exactly equal, or equal+1 or equal-1".

Your problem statement seems to assume integer operations: "If the number is exactly equal, or exactly equal+1 or exactly equal-1." The tests given by ikegami here are not quite equivalent to your OPed test if the numbers are not integers: (update: ikegami already assumed integers in his reply, but the following examples are still pertinent.) | If the numbers are not integers:

c:\@Work\Perl\monks>perl -wMstrict -le "my $x = 2; my $y = 2.00000000000000123; print qq{$x $y}; ;; if ($x == $y or $x == $y-1 or $x == $y+1) { print 'in exact range'; } if ($y-1 <= $x && $x <= $y+1) { print 'in <= range'; } if (abs($y-$x) <= 1) { print 'in abs range'; } " 2 2 in <= range in abs range
Remember that Perl numbers are essentially floating-point doubles. This may introduce some twists and pitfalls. (Update: Certain combinations of operations may produce a number like 2.00000000000000123 that may appear, in certain circumstances, to be an integer, but isn't. See What Every Computer Scientist Should Know About Floating-Point Arithmetic.) One way to force integer operations is with the integer pragma:
c:\@Work\Perl\monks>perl -wMstrict -le "use integer; ;; my $x = 2; my $y = 2.00000000000000123; print qq{$x $y}; ;; if ($x == $y or $x == $y-1 or $x == $y+1) { print 'in exact range'; } if ($y-1 <= $x && $x <= $y+1) { print 'in <= range'; } if (abs($y-$x) <= 1) { print 'in abs range'; } " 2 2 in exact range in <= range in abs range

Update: Changed both code examples to use the floating-point number 2.00000000000000123 (vice 2.5) for $y.


Give a man a fish:  <%-{-{-{-<


In reply to Re: IF condition with a range (updated) by AnomalousMonk
in thread IF condition with a range by Anonymous Monk

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.