7

How to script a comparison of a number against a range?

1 is not within 2-5

or

3 is within 2-5

7 Answers 7

19

It's even better in Perl6.

Chained comparison operators:

if( 2 <= $x <= 5 ){
}

Smart-match operator:

if( $x ~~ 2..5 ){
}

Junctions:

if( $x ~~ any 2..5 ){
}

Given / When operators:

given( $x ){
  when 2..5 {
  }
  when 6..10 {
  }
  default{
  }
}
14
  • So much of Perl 6 looks awesome that I think I can forgive the few things that don't.
    – Chris Lutz
    Feb 28, 2009 at 5:55
  • 1
    Given/When also works in 5.10, it's one of the things that was back-ported to Perl5. Feb 28, 2009 at 15:09
  • 2
    Truly, when Perl 6 arrives it will change the way your grandchildren write code. Feb 28, 2009 at 15:32
  • Since the task can be solved without difficulty in existing Perls, it makes me cringe to see that this answer -- which lists a pile of incredibly marginal improvements from a language that doesn't exist yet -- should be at the top. I'm tempted to -1 this just to reduce the cringe factor. Mar 1, 2009 at 5:18
  • 1
    @j_random_hacker: "doesn't exist yet" is out of date FUD. you could say "not yet released", but it sure does exist: perl.com/download.csp#perl6
    – ysth
    Mar 1, 2009 at 11:07
13

In Perl:

if( $x >= lower_limit && $x <= upper_limit ) {
   # $x is in the range
}
else {
   # $x is not in the range
}
7
  • appreciate the quick replies!
    – noobbk
    Feb 28, 2009 at 4:46
  • Um ... I think some sigils are missing. Perl probably does the right thing but you might also want to keep in mind that perl uses floating point as default for numbers, so you have the potential for the 0.999999... == 1.0 problem. But I'm an old Fortran programmer, so discount my words accordingly.
    – jaredor
    Feb 28, 2009 at 5:25
  • Recent perls try hard to keep integers stored as such.
    – ysth
    Mar 1, 2009 at 4:25
  • thanks for the edits brian. The invisible $ in perl frequently bites me.
    – Adnan
    Mar 1, 2009 at 5:25
  • I prefer if( lower_limit <= $x && $x <= upper_limit ). Mar 1, 2009 at 14:59
11

In bash:

$ if [[ 1 -gt 2 && 1 -lt 5 ]]; then echo "true"; fi
$ if [[ 3 -gt 2 && 1 -lt 5 ]]; then echo "true"; fi
true
2
  • Just for fun: if seq $lo $hi | grep -w $num; then echo yes indeedy sir; fi
    – ysth
    Mar 1, 2009 at 4:22
  • 3
    if (( lower <= x && x <= upper )); then echo true; fi Mar 1, 2009 at 20:57
10

The smart match operator is available in Perl 5.10, too:

if ( $x ~~ [2..5] ) {
    # do something
}
2
  • yeah, and any {$_ == $x} 2..5 can be done using List::MoreUtils
    – hillu
    Mar 1, 2009 at 21:37
  • or Quantum::Superpositions. but that or L::MU's any are so horrifically expensive that it curdles my prematurely optimizing blood to think of using them for trivial tests.
    – ysth
    Mar 2, 2009 at 2:20
2

In Bash:

x=9; p="\<$x\>"; if [[ $(echo {10..20}) =~ $p ]]; then echo true; else echo false; fi

Edited to correctly handle conditions as noted in the comment below.

rangecheck () { local p="\<$1\>"; if [[ $(echo {10..20}) =~ $p ]]; then echo true; else echo false; fi; }
for x in {9..21}; do rangecheck "$x"; done
false
true
.
.
.
true
false
2
  • Fails as if [[ $(echo {10..20}) =~ 9 ]]; then echo true; fi returns true. Good idea though, could be improved? (I lack much bash knowledge)
    – sharat87
    Nov 8, 2011 at 13:32
  • @ShrikantSharat: I have edited my answer to correct that problem. Thanks for pointing it out. Nov 9, 2011 at 0:15
1

In perl

grep {/^$number$/} (1..25);

will give you a true value if the number is in the range and a false value otherwise.

For example:

[dsm@localhost:~]$ perl -le 'print "has `$ARGV[0]`" if grep {/^$ARGV[0]$/} (1..25)' 4
has `4`
[dsm@localhost:~]$ perl -le 'print "has `$ARGV[0]`" if grep {/^$ARGV[0]$/} (1..25)' 456
[dsm@localhost:~]$ 
1
  • "will give you a non-empty list" - actually, perl will return true/false when grep is used in scalar context (like in your examples) - and newer perls also short circuit in this case, iirc.
    – user55400
    Mar 2, 2009 at 13:22
1

The [[ version of test has supported regular expressions since Bash 3.0.

[[ 3 =~ ^[2-5]$ ]]; echo $? # 0

The numeric comparison operators in test sometimes return an error if the input isn't numeric:

[[ 1a -ge 1 ]]; echo $? # value too great for base (error token is "1a")
[[ '$0' -le 24 ]] # syntax error: operand expected (error token is "$o")

You can test if the input is an integer with =~:

x=a23; [[ "$x" =~ ^[0-9]+$ && "$x" -ge 1 && "$x" -le 24 ]]; echo $? # 1
x=-23; [[ "$x" =~ ^-?[0-9]+$ && "$x" -ge -100 && "$x" -le -20 ]]; echo $? # 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.