Assuming integers, and given your single and very specific test case, I think ++ikegami's second solution is probably the best.

Here's a solution that's less compact and less efficient:

if ($x =~ /^(?:${\join "|", $y-1 .. $y+1})$/)

My test:

$ perl -E 'my $y = 3; say "$_: ", /^(?:${\join "|", $y-1 .. $y+1})$/ ? + "YES" : "NO" for 1..5' 1: NO 2: YES 3: YES 4: YES 5: NO

Having said that, given another test case with a larger range not centered exactly around $y, this technique may be more appealing. Consider

if ($x==$y or $x==$y-1 or $x==$y-2 or $x==$y-3 or $x==$y+1)

vs.

if ($x =~ /^(?:${\join "|", $y-3 .. $y+1})$/)

My test:

$ perl -E 'my $y = 3; say "$_: ", /^(?:${\join "|", $y-3 .. $y+1})$/ ? + "YES" : "NO" for -1..5' -1: NO 0: YES 1: YES 2: YES 3: YES 4: YES 5: NO

And those hard-coded numbers (in $y-3 and $y+1) could be variables: perhaps, $min_below_y and $max_above_y.

So, as I said, in your very specific example, this technique wouldn't be the best choice; however, in a more general scenario, it could be a better choice.

— Ken


In reply to Re: IF condition with a range by kcott
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.