Search code examples
perlattributesmoose

Perl Moose attributes with minimum, maximum, and default value


Using Moose, it's possible to create attributes having a default value. I have a set of attributes which all have a minimum, maximum and a default value. They are attributes representing a scale (such as Tk::Scale).

Currently, I have at least 3 attributes: current & default:

has 'attr' => (is => 'rw', isa => 'Int', default => 300, lazy => 1, clearer => '_clear_attr');

min:

has 'attr_min' => (is => 'rw', isa => Int', default => 100);

max:

has 'attr_max' => (is => 'rw', isa => Int', default => 1000);

Is it possioble to have all four (current, default, min, max) in one attribute?


Solution

  • I think you want to create a validation rule.

    use Moose::Util::TypeConstraints;
    
    subtype 'ScaleVal',
       as 'Int',
       where { 100 <= $_ && $_ <= 1000 };
    
    has attr => (
       is      => 'rw',
       isa     => 'ScaleVal',
       default => 300,
    );