Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Moose and default values

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


in reply to Moose and default values

I wrote PerlX::Maybe precisely for this purpose!

use v5.14; use strict; use warnings; use PerlX::Maybe; package Foo { use Moose; has foo => (is => 'ro', default => 'whatever'); } my $value = 'hello'; print Foo->new(maybe foo => $value)->dump; $value = undef; print Foo->new(maybe foo => $value)->dump;

As you can see, the maybe keyword is applied at the "consumer side" - i.e. in the code that is using the class.

Within the class itself, you could try MooseX::UndefTolerant though that has a major caveat listed in the documentation!

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


Comment on Re: Moose and default values
Select or Download Code
Re^2: Moose and default values
by morgon (Deacon) on Feb 20, 2013 at 22:32 UTC
    Nice, but why does it live in "PerlX" and not in "Moose" or "MooseX"?
      Probably you can use it outside Moose, too.
      لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

        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
Re^2: Moose and default values
by Ovid (Cardinal) on Feb 21, 2013 at 08:48 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1019853]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2015-04-19 15:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Who makes your decisions?







    Results (360 votes), past polls