http://www.perlmonks.org?node_id=946288


in reply to Range Operator in If Statement

If you insist in using a range-/list-op, you could do:

if ( grep { $ref == $_ } 1..8 ) { ... }
But personally, I would rather use something like
if ( $ref >= 1 and $ref <= 8 ) { ... }
or maybe
if ( $ref =~ /^[1-8]$/ ) { ... }

Update: (in response to OP's reply below) With a modern Perl, you could use given/when:

use v5.10; use strict; use warnings; my @tests = qw(1 9 17 25 33); my $range_25_32 = [25..32]; # alternatve, maybe(?) faster for my $ref ( @tests ) { given ( $ref ) { when ( [1..8] ) { say "A $ref" } when ( [9..16] ) { say "B $ref" } when ( [17..24] ) { say "C $ref" } when ( $range_25_32 ) { say "D $ref" } default { say "ELSE $ref" } } }
Output:
A 1 B 9 C 17 D 25 ELSE 33
With the given ranges in the example below, some bitwise operators might also work.

Replies are listed 'Best First'.
Re^2: Range Operator in If Statement
by mmartin (Monk) on Jan 04, 2012 at 20:55 UTC
    Hey perlbotics, thanks for you QUICK reply...

    Ohh ok I thought I could use the range operator for this type of thing, but guess not.

    I wanted to use that because it seemed like it was the "shorthand" way of doing it.
    Wanted a short way because I needed a whole bunch of those statements and I didn't want to have a ton of these statements:
    if ($ref >= 1 && $ref <= 8) { ...... } if ($ref >= 9 && $ref <= 16) { ...... } if ($ref >= 17 && $ref <= 24) { ...... } if ($ref >= 25 && $ref <= 32) { ...... } #....more checks

    But if that's what you recommend then I'll just use my original way I had like above and like you had...

    Thanks again for the reply,
    Matt
      This looks like a power of 2 problem. If you could give us some more detail about what you are doing, I think some very efficient solutions might be forthcoming.
      When classifying by intervals, better try $case = int( ($ref-1) / 8 ) , so you only have to test for the results 0,1,2,3...

      DB<104> for $ref (1,8,9,16,17,24,25,32) { print "$ref: ", int(($ref-1) +/8), "\n" } 1: 0 8: 0 9: 1 16: 1 17: 2 24: 2 25: 3 32: 3

      Cheers Rolf

      If you have multiple consecutive intervals, it's better to use an elsif cascade, such as

      if ($ref <= 8) { say "ref is at most 8."; } elsif ($ref <= 16) { say "ref is above 8 but at most 16." } elsif ($ref <= 24) { say "ref is above 16 but at most 24." } elsif ($ref <= 32) { say "ref is above 24 but at most 32." } else { sat "ref is above 32." }
      The elsif part means that if the previous condition was found true, the next one is not tested for, so eg. if $ref = 5 then the first branch is executed, the rest of the tests and branches are skipped.