FryingFinn has asked for the wisdom of the Perl Monks concerning the following question:
I'm fairly new to Moose & I cannot seem to figure out this problem: I have a string attribute to which I wish to prepend another string... I try with builder: no luck; I tried w BUILDARGS which works when an instance is initiated, but not when I try to change the attribute...
My testing module:
package Test; use Moose; my $prepend = '/some_string/'; has 'fname' => (is => 'rw', isa => 'Str'); has 'appended' => ( is => 'rw', isa => 'Str', # lazy => 1, #builder => 'set_appended' ); 1; sub BUILDARGS { my $class = shift; my %args = ref $_[0] ? %{$_[0]} : @_; $args{appended} = $prepend . $args{appended} if exists $args{appe +nded}; return \%args; } sub set_appended { my $self = shift; my $value = $self->appended; return $prepend . $value; }
My test program
use 5.010; use strict; use warnings; use lib "."; use Test; my $t = new Test( fname => "fred", appended => "this_is_appended_string"); say $t->fname; say $t->appended; $t->appended ('another_string'); say $t->appended;
The output
Thx in advance..fred /some_string/this_is_appended_string another_string
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Prepend a Moose attribute when changed
by 1nickt (Canon) on Feb 08, 2019 at 02:45 UTC | |
|
Re: Prepend a Moose attribute when changed
by Haarg (Priest) on Feb 08, 2019 at 13:19 UTC | |
|
Re: Prepend a Moose attribute when changed
by tobyink (Canon) on Feb 08, 2019 at 14:45 UTC |