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

Hello,

I have a problem with a variable that was defined

has re =>(is => 'rw', isa =>'RegexpRef', default => '')

In BUILD I specified

$self->re(qr/^[0-9]+$/); (gave a contraint error; OK, no reference)

Then I tried

my $rx = qr/^[0-9]+$/; $self->re(\$rx); # or $self->re(\qr/^[0-9]+$/);

Both also resulted in a constraint error.

How should I use RegexpRef?
Thanks for your help.

K.D.J.

Replies are listed 'Best First'.
Re: Moose RegexpRef
by tobyink (Canon) on Dec 14, 2014 at 21:17 UTC

    Type constraint error is probably from the default. Your default is a string, not a regexp ref. Just don't set a default at all.

Re: Moose RegexpRef
by Athanasius (Archbishop) on Dec 15, 2014 at 09:51 UTC

    Hello kdjantzen,

    As tobyink says, you’re better off not setting a default value — especially as you overwrite it immediately in sub BUILD anyway. However, in the unlikely event that you really do have a use case for this, follow the advice of the error message generated when setting default => \qr//:

    References are not allowed as default values, you must wrap the defaul +t of 're' in a CODE reference (ex: sub { [] } and not []) at ...

    For example, this works:

    #! perl use strict; use warnings; package Test { use Moose; has re => (is => 'rw', isa => 'RegexpRef', default => sub { qr/abc +/; }); sub BUILD { my $self = shift; $self->re(qr/^[0-9]+$/); } sub match { my ($self, $string) = @_; return $string =~ $self->re ? 'matches' : 'does not match'; } } my $t = Test->new(); print "$_ ", $t->match($_), "\n" for 'abc123def', '456';

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Hello,
      thank you for the quick reply.
      It works!!
      K.D.J.