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.