Allows numbers that do not go higher or lower than a given ceiling and floor.

Update: Tie::NumRange-0.01 is on CPAN (or will be when your local mirror refreshes), as well as my modules page.

package Tie::NumRange; # (initial, low, high) sub TIESCALAR { my $class = shift; my $self = bless [ @_ ], $class; $self->STORE($_[0]); # just in case return $self; } sub STORE { my ($self,$val) = @_; return $self->[0] = $self->[1] if defined($self->[1]) and $self->[1] > $val; return $self->[0] = $self->[2] if defined($self->[2]) and $self->[2] < $val; return $self->[0] = $val; } sub FETCH { $_[0][0] } 1;
Very simple concept really, which I got from $code_or_die's recent node for shifting RGB values. Here's an example use:
use Tie::NumRange; my ($r,$g,$b); tie $r, Tie::NumRange => (0, 0, 255); tie $g, Tie::NumRange => (0, 0, 255); tie $b, Tie::NumRange => (0, 0, 255); $r = 100; # fine $g = 200; # fine $b = 300; # set to 255 $b -= 150; # fine, is now 105 $g -= 150; # fine, is now 50 $r -= 150; # set to 0
The arguments to tie() are the variable, the class, the inital value, the floor, and the ceiling. To make a number with no least value, send undef as the floor (likewise for the ceiling).

Replies are listed 'Best First'.
Re: Tie::NumRange
by boo_radley (Parson) on Feb 28, 2001 at 08:51 UTC
    This is a keen idea, and a nice implementation. I wonder -- could it throw a warning under -w when a value's out of range?
      Not on your life!

      Oh, wait. Wrong answer. Sure it could. I could add that to version 0.02 on CPAN today.

      japhy -- Perl and Regex Hacker