Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re^4: Moose and default values

by tobyink (Abbot)
on Feb 20, 2013 at 22:39 UTC ( #1019857=note: print w/replies, xml ) Need Help??

in reply to Re^3: Moose and default values
in thread Moose and default values

Indeed; it has no ties to Moose. It's simply a function that takes a list and returns a (possibly smaller) list. While it's handy to use it with Moose/Mouse/Moo constructors, it can be used with any functions that take a list of key-value pairs that you want to filter out undefs from.

package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name

Replies are listed 'Best First'.
Re^5: Moose and default values
by morgon (Curate) on Feb 20, 2013 at 22:42 UTC
    It's nice (and only 10 lines of code :-=).

    But say I now wanted not only undefs but everything that is false (e.g. also an empty string) to trigger the default?

    Does Moose not have any mechanics for that?

      Maybe something along the lines of:

      around BUILDARGS => sub { my $orig = shift; my $self = shift; my $params = $self->$orig(@_); $params->{$_} || delete $params->{$_} for qw/ foo bar /; return $params; };

      This will discard false parameters for the "foo" and "bar" attributes.

      package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name
        Sure you can always hack togther something, I was more looking for a way to do such things declaratively...

        But your Haskell-ripoff is a at least a step forward - thanks.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1019857]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (8)
As of 2018-05-22 14:57 GMT
Find Nodes?
    Voting Booth?