in reply to Match Numeric Range
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.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Match Numeric Range
by PilotinControl (Pilgrim) on Aug 18, 2015 at 13:53 UTC | |
by Your Mother (Archbishop) on Aug 18, 2015 at 14:14 UTC | |
by PilotinControl (Pilgrim) on Aug 18, 2015 at 14:39 UTC |