Re: Predicate
[email protected] (Paul Driver)
| Newsgroups | perl.moose |
|---|---|
| Message-ID | <[email protected]> |
This is actually the intended behavior, I believe. The rub is Perl's
notion of undef - it is a value, but it also means "null" in a lot of
context. It doesn't help that there's an undef keyword that "undef"s
things. At any rate, rather than setting a value to undef, you can
delete the value - there is a helper similar to predicate called
'clearer' that will cause predicate to once again return false.
Package Foo;
use Moose;
has item => (
is => 'ro',
isa => 'Str|Undef',
predicate => 'has_item',
clearer => 'delete_item'
);
[snip]
my $f = Foo->new
$f->has_item # => 0
$f->item('value!')
$f->item # =>'value'
$f->has_item # => 1
$f->item(undef)
$f->item # => undef
$f->has_item # => 1
$f->delete_item;
$f->item # => undefined
$f->has_item # => 0
On Apr 4, 2008, at 3:25 PM, Piotr Jackowski wrote:
> Hi Developers,
>
> Here http://search.cpan.org/~stevan/Moose/lib/Moose/Cookbook/
> Recipe3.pod I
> can read:
> "The next attribute option is new, though: the predicate option.
> This option
> creates a method which can be used to check whether a given slot
> (in this
> case parent) contains a defined value. In this case it will create
> a method
> called has_parent. Quite simple, and quite handy too."
>
> Truly said predicate checks if value was set or not.
> When I will set attribute with 'undef' actually predicate will say
> 'true'.
> Moose version 0.40.
>
> Please see this simple test:
>
> #!/perl
>
> use strict;
> use warnings;
>
> use Carp;
> use Data::Dumper;
>
> use Test::More qw(no_plan);
> use Test::Exception;
>
> package TestPredicate;
> use Moose 0.40;
>
>
> has 'item' => ( is => 'ro',
> isa => 'Str|Undef',
> predicate => 'has_item');
>
> no Moose;
>
> package main;
>
>
> my $obj1 = TestPredicate->new();
> ok( !$obj1->has_item, "I don't have value, because I didn't give
> anything");
>
>
> my $obj2 = TestPredicate->new( item => undef );
> ok( !$obj2->has_item, "I shouldn't have item, but I set undef");
>
>
>
> I miss something or there is a bug ?
>
>
> Thanks!
> Peter