Have an idea?

Visit Sawtooth Software Feedback to share your ideas on how we can improve our products.

Many "in between" conditions for unverified perl syntax

Hi. Is there unverified perl syntax which allows me to state numeric variables "in between" ranges?

Imagine I have a variable (named: level) with 30 total values. I have a condition that applies to a handful of those values, like:

elsif(VALUE("level") == 5 || VALUE("level") == 6 || VALUE("level") == 7 || VALUE("level") == 15 || VALUE("level") == 21 || VALUE("level") == 22 || VALUE("level") == 23)


Basically, is there a way to write it such that I effective say:
elsif(VALUE("level") == 5 || VALUE("level") == 6 || VALUE("level") == 7 || VALUE("level") == 15 || VALUE("level") == "between 21 and 23")
asked Jan 26 by WTW_cal Bronze (1,375 points)
retagged Jan 26 by Walter Williams

1 Answer

0 votes
This script will evaluate to true iff level is between 21 and 23 inclusive:

VALUE("level") >= 21 && VALUE("level") <= 23


You can use this in your line of code, but make sure to keep order of operation in mind.  This version of your code will simply perform each AND (&&) and OR (||) from left to right:

elsif(VALUE("level") >= 5 && VALUE("level") <= 7 || VALUE("level") == 15 || VALUE("level") >= 21 && VALUE("level") <= 23)


What you want to do is add parentheses around your "between X and Y" parts so that those parts are evaluated first, then all of the ORs are ran:

elsif((VALUE("level") >= 5 && VALUE("level") <= 7) || VALUE("level") == 15 || (VALUE("level") >= 21 && VALUE("level") <= 23))


Lines with that many parentheses can be hard to read.  You can make it easier to read if you pull the equality tests out before your if-elsif-else code:

my $level = VALUE("level");
my $inRange1 = $level >= 5 && $level <= 7;
my $inRange2 = $level == 15;
my $inRange3 = $level >= 21 && $level <= 23;

if (...)
{
    ....
}
elsif($inRange1 || $inRange2 || $inRange3)
{
    ...
}
answered Jan 26 by Zachary Platinum Sawtooth Software, Inc. (86,725 points)
...