Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Moose Attribute constraint: Regex OR undef

by hoppfrosch (Scribe)
on Oct 31, 2016 at 12:11 UTC ( #1175012=perlquestion: print w/replies, xml ) Need Help??

hoppfrosch has asked for the wisdom of the Perl Monks concerning the following question:


I want to use Moose type constraints for an attribute which could either be undefined or - if the attribute is provided on new() - match a given RegEx.

What I currently have is:

has 'attr' => ( is => 'ro', isa => subtype( as 'Str', where { /$regEx/ } ), required => 0 );

I cannot figure out, where to put the undef to - or I have an incorrect syntax. Any hint welcome ...

Replies are listed 'Best First'.
Re: Moose Attribute constraint: Regex OR undef
by 1nickt (Canon) on Oct 31, 2016 at 12:57 UTC

    Maybe you need Maybe?

    subtype 'MyMatch', as 'Str', where { /$regEx/ }, message { "$_ didn't match" }; has 'attr' => ( is => 'ro', isa => 'Maybe[MyMatch]', required => 0 );
    See doc:
    The Maybe[`a] type deserves a special mention. Used by itself, it doesn't really mean anything (and is equivalent to Item). When it is parameterized, it means that the value is either undef or the parameterized type. So Maybe[Int] means an integer or undef.

    Hope this helps!

    The way forward always starts with a minimal test.
      Silly me: I was close to the same solution - but I failed due to the usage of round brackets instead of square brackets with Maybe[....]
Re: Moose Attribute constraint: Regex OR undef
by Corion (Patriarch) on Oct 31, 2016 at 12:19 UTC

    Can you show us a short program that shows the intended usage of your class? Also, what errors do you currently get (or not)?

    I assume that where takes a subroutine reference which gets the thing to test in $_, so maybe the following already is enough?

    ... where { not defined $_ or $_ =~ /$regEx/ }

    Update: Negated the expression, thanks to 1nickt

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1175012]
Approved by marto
Front-paged by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (5)
As of 2022-06-29 07:12 GMT
Find Nodes?
    Voting Booth?
    My most frequent journeys are powered by:

    Results (96 votes). Check out past polls.