When creating a class quickly I often use Class::Accessor but this time I have many setters that need to validate the values passed to them. I have implemented a simple case when using regular expressions for validations but I already know I have other setters that will need to check against a fixed set of values and then who knows what else.
package MyClass; use base qw(Class::Accessor); sub set { my ($self, $field, $value) = @_; my %VALID = ( fname => qr/^[\w-]+$/, ); if (defined $VALID{$field}) { if (ref $VALID{$field} eq 'Regexp') { if ($value =~ $VALID{$field}) { $self->{$field} = $value; } else { die "Invalid value '$value'\n"; } } else { die "Unknown VALIDATOR"; } } } __PACKAGE__->mk_accessors(qw(fname));
I don't want to reinvent the wheel and I guess someone has implemented something like this, I just could not find it yet on CPAN.

In reply to accessor generation with constraints by szabgab

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.