in reply to IF condition with a range

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