Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Moose Attribute Default Dependency

by dpath2o (Acolyte)
on Nov 12, 2013 at 21:49 UTC ( [id://1062275]=perlquestion: print w/replies, xml ) Need Help??

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

How would one do this (see below) with Moose?
has 'x' => ( is => 'rw', isa => 'str', default => 'was once a ' ); has 'y' => ( is => 'rw', isa => 'str', default => $self->{x}.'y' );

Replies are listed 'Best First'.
Re: Moose Attribute Default Dependency
by boftx (Deacon) on Nov 12, 2013 at 21:57 UTC

    I would say that your declaration for 'x' is fine as is. It is your declaration for 'y' that needs to be lazy and have a builder because you can't depend upon 'x' to have been defined before 'y' is.

    has 'y' => ( is => 'rw', isa => 'str', lazy => 1, builder => '_build_y' ); sub _build_y { my $self = shift; return $self->{x}.'y' ); }

    Update:

    You should bear in mind that while this would okay for when the object is being constructed, you should also consider the case if 'x' can be changed later on. At that point 'y' would probably not hold what you want, so you should consider reading about predicates and clearers, as well as triggers.

    The answer to the question "Can we do this?" is always an emphatic "Yes!" Just give me enough time and money.
      Thanks superdoc. I'll go away, read and test some more.

        As an aside, you should always use object accessors instead of raw object elements unless you have a very good reason not to, especially with Moose objects, so that you take full advantage of any modifiers such as 'before', 'around' and 'after' as well as triggers that may be present. Direct access to the element bypasses all of those features which will probably result in undesired side-effects.

        # use this: $obj->x . 'y'; # and not this: $obj->{x} . 'y';
        The answer to the question "Can we do this?" is always an emphatic "Yes!" Just give me enough time and money.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1062275]
Approved by kcott
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2024-04-25 19:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found