PilotinControl:

If you're just wanting to simplify conditional statements like the ones you've shown, I typically use a function like this:

use strict; use warnings; sub between { my ($min, $val, $max) = @_; return $val>=$min && $val<=$max; } for my $range (450, 475, 500, 550, 450, 350, 250, 100) { print "Range: $range\n"; if (between(300, $range, 400)) { exit; } if (between(425, $range, 500)) { print "LIGHTS ON\n"; } }
$ perl t.pl Range: 450 LIGHTS ON Range: 475 LIGHTS ON Range: 500 LIGHTS ON Range: 550 Range: 450 LIGHTS ON Range: 350

If you need to get fancier and build your functions dynamically (such as reading the values from a file), I tend to use a closure to generate them:

#!/usr/bin/env perl use strict; use warnings; # Build the functions my @tests; while (<DATA>) { my ($min, $max, $message) = split /\s+/, $_, 3; push @tests, make_test_function($min, $max, $message); } my $range = 0; while ($range < 600) { print "Range: $range\n"; for my $test (@tests) { $test->($range); } $range += int(100*rand); } sub make_test_function { my ($min, $max, $message) = @_; return sub { my $val = shift; print $message if $val >= $min and $val <= $max; } } __DATA__ 100 350 In range A 200 500 In range B 300 400 In range C
$ perl t.pl Range: 0 Range: 10 Range: 10 Range: 25 Range: 56 Range: 144 In range A Range: 208 In range A In range B Range: 254 In range A In range B Range: 323 In range A In range B In range C Range: 379 In range B In range C Range: 468 In range B Range: 530 Range: 550 Range: 557

...roboticus

When your only tool is a hammer, all problems look like your thumb.


In reply to Re: Match Numeric Range by roboticus
in thread Match Numeric Range by PilotinControl

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.