http://qs1969.pair.com?node_id=74833
Category: Miscellaneous
Author/Contact Info perl@simonflack.com
$code or die
http://www.simonflack.com
Description: This module lets you define a range of dates or numeric values and will return which set a given test value is a member of.

Personally, this will save me precious minutes by not having to do a lot of if .. then statements. It's not highly advanced or anything, just quite useful I think. e.g. want to do something depending on the value of x, but don't want the values to be hard-coded or difficult to change\add to?

Please let me know if you have any questions or suggestions - specifically, I'm looking for a nice way of removing that nasty eval statement... Also, do you think it's worth submitting this to CPAN, if so is Set::Range OK?

POD to follow...
package Set::Range;
require Exporter;

use constant DATE_RANGE        => 1;
use constant NUM_RANGE        => 2;
use constant TIME_RANGE        => 3;
use constant EU_DATE_RANGE    => 4;

@ISA = qw(Exporter);
@EXPORT = qw(DATE_RANGE EU_DATE_RANGE NUM_RANGE TIME_RANGE);

sub new {
    my $self = shift;
      my $range = shift;
      return bless $range, $self;
}


sub getSet {
    my ($self, $var, $type) = @_;
    $type = NUM_RANGE unless $type;

    if (($type == DATE_RANGE) || ($type == EU_DATE_RANGE)) {
        $var = _timify($var, $type);
    }

    my $state = 0;
    foreach $state (keys %$self) {
        my ($u, $l) = ($self->{$state}->{upper},
                $self->{$state}->{lower});
        
        if (($type == DATE_RANGE) || ($type == EU_DATE_RANGE)) {
            $upper= _timify($u, $type);
            $lower= _timify($l, $type);
        }
        
        my ($uinc, $linc, $result);
        if ($self->{$state}->{upper_inclusive}) {
            $uinc = '>=';
        } else { $uinc = '>' }
        
        if ($self->{$state}->{lower_inclusive}) {
            $linc = '>=';
        } else { $linc = '>' }
    
        $result = 
        eval "$state if (($u $uinc $var) && ($var $linc $l))";
        
        return $result if $result;

    }
    return 0;
}


sub _timify {
    my ($u, $type) = @_;
    
    require Date::Calc;

    if ($type == EU_DATE_RANGE) {
        $u = Date::Calc::Date_to_Days(Date::Calc::Decode_Date_EU($u));
    } else {
        $u = Date::Calc::Date_to_Days(Date::Calc::Decode_Date_US($u));
    }
    
    
    return $u;    
}