morgon has asked for the wisdom of the Perl Monks concerning the following question:
Monks,
assume you have a script that takes input from the command-line and passes that on to a Moose-class Foo, i.e.
When no bar-value is supplied on the command-line the class should use a default instead (I want to keep the defaults in the class-definition not in the script).use Foo; my ($bar) = @ARGV; my $foo = Foo->new( bar => $bar );
A first try does not what I want:
because then when the command-line is empty the constructor is called with "bar" => undef, setting the attribute to undef and not to the intended default.package Foo; use Moose; has bar => (is => "ro", default => "whatever");
I usually do this instead:
This does work, instantiating via Foo->new( bar => undef ) sets bar to the default, but the downside is that the default-value is not declared with the attribute but buried in the BUILDer-code and to make this work the attribute has to be "rw".package Foo; use Moose; has a => (is => "rw"); sub BUILD { my($this, $args)=@_; $this->bar("whatever") unless defined $args->{bar}; }
So I wonder if there is a better way to achieve this - i.e. declaratively defining attribute-defaults for ro-attributes that also get applied when undef is passed in.
Many thanks!
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Moose and default values
by tobyink (Canon) on Feb 20, 2013 at 22:25 UTC | |
by Ovid (Cardinal) on Feb 21, 2013 at 08:48 UTC | |
by morgon (Priest) on Feb 20, 2013 at 22:32 UTC | |
by choroba (Cardinal) on Feb 20, 2013 at 22:34 UTC | |
by tobyink (Canon) on Feb 20, 2013 at 22:39 UTC | |
by morgon (Priest) on Feb 20, 2013 at 22:42 UTC | |
| |
Re: Moose and default values
by 7stud (Deacon) on Feb 21, 2013 at 05:39 UTC | |
by tobyink (Canon) on Feb 21, 2013 at 13:17 UTC | |
by 7stud (Deacon) on Feb 22, 2013 at 00:06 UTC | |
by tobyink (Canon) on Feb 22, 2013 at 11:41 UTC |
Back to
Seekers of Perl Wisdom