DavidSzczesniak
12/22/2017 - 12:47 PM

Predicate and clearer

These allow you to explicitly distinguish between a false or undefined attribute value and a value which has not been set.

\!h # Predicate - tells you whether or not a given attribute is currently set. 
# If the attribute is explicitly set to 'undef' or some other false value, this will still return true because they are set after all.

\!h # Clearer - unsets an attribute
# Not the same as setting the value to 'undef'- but you can only distinguish between the two using predicate.

\!h # Code to illustrate relationship between an accessor, predicate and clearer method.

package Person;

use Moose;

has 'ssn' => ( # create attribute
  is => 'rw', # make it read-write
  clearer => 'clear_ssn', # provide name for clearer
  predicate => 'has_ssn', # provide name for predicate
  # ^ By default, Moose doesn't make them for you
  )
  
  ...
  
  my $person = Person->new(); # create object instance in Person class
  $person->has_ssn; # false, no value is set
  
  $person->ssn(undef); # sets a value of 'undef'
  $person->ssn; # returns the value
  $person->has_ssn; # returns true now because $person has a value
  
  $person->clear_ssn; # unset current value
  $person->ssn; # also returns undef, this time it isn't explicitly set though
  $person->has_ssn; # false because undef is there by default, from a lack of value
  
  $person->ssn('123-45-6789'); # set new value
  $person->ssn; # returns new value; '123-45-6789'
  $person->has_ssn; # true
  
  my $person2 = Person->new(ssn => '111-22-3333'); # make new variable under the Person class, with the attributes of 'ssn' and the value '111-22-3333'.
  $person->has_ssn; # true