Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Moose Attribute constraint: Regex OR undef

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

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

Hi

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[....]
      Thanks!
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?
Username:
Password:

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
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (4)
As of 2024-03-29 09:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found