Moose can take care of this kind of thing very easily. Here is a simple translation of what you did.

package MyClass; use Moose; use Moose::Util::TypeConstraints; has 'fname' => ( is => 'rw', isa => subtype('Str', where { /^[\w-]+$/ }), );
The 'isa' becomes a anon-subtype of "Str" (the String type in Moose) but with the additional validtion in the where clause. A better way to do this though would be make it an official subtype, so that you can then re-use it in other attribute accessors.
package MyClass; use Moose; use Moose::Util::TypeConstraints; subtype 'StringWithDashes' => as 'Str' => where { /^[\w-]+$/ }; has 'fname' => ( is => 'rw', isa => 'StringWithDashes' ); has 'lname' => ( is => 'rw', isa => 'StringWithDashes' );
Moose can also handle delegating the validation as well, this would match the example of one of the other posters.
use Email::Valid; has 'email' => ( is => 'rw', isa => subtype('Str', where { Email::Valid->address($_) }) );
Of course this only barely scratches the surface of accessor validation in Moose. You can also set attributes to be required in the constructor, you can set defaults for those attributes as well. Then you can get into coercion, which allows you to easily convert one value into another. The Moose::Cookbook has examples for all these things. And if you want to extend those same types and use them in method validation as well, there is the more lightweight MooseX::Params::Validate and the more featureful MooseX::Method to choose from.

-stvn

In reply to Re: accessor generation with constraints by stvn
in thread 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.