http://www.perlmonks.org?node_id=1039921


in reply to Restricting a scalar to certain values

Type::Tie can be used to tie a scalar, array or hash variable to a type constraint. It supports Type::Tiny, Moose::Meta::TypeConstraint and MooseX::Types type constraints (and probably Mouse::Meta::TypeConstraint and MouseX::Types, though these are untested).

#!/usr/bin/env perl use strict; use warnings; use Type::Utils qw(enum); use Type::Tie; my $scalar; ttie $scalar, enum ["foo", "bar"]; $scalar = "foo"; # ok $scalar = "bar"; # ok $scalar = "baz"; # dies

Update: note though that tied scalars are significantly slower than untied. So an idea might be to tie your scalars in your development environment, and keep them untied in production. This can be achieved using something like:

use constant DEBUG => !!$ENV{DEVELOPMENT_SERVER}; my $scalar; ttie $scalar, enum ["foo", "bar"] if DEBUG;
package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name