Moose attribute exists

I am trying to iterate over the attributes of a Moose object by printing the value of the attributes without involving any lazy collectors (albeit printing if the value of the attribute exists).

My code looks like this:

for my $attr ($object->meta->get_all_attributes) {
    my $name = $attr->name;

    # Lazy attributes that have not already been generated will not
    # exist in the object hash.
    next unless exists $object->{$name}

    my $value = $object->$name;
    print $value;
}

Is there a way to test an object using Moose that will tell me if the attribute value exists without changing the Moose class itself?

i.e. a more elegant alternative to the โ€œnext if nonexistentโ€ line in the code above

Thanks for any help and attention :)

+3
source share
1 answer

Reading a Moose :: Meta :: Class document points to Class :: MOP :: Class and Class :: MOP :: Attribute .

:

foreach my $attr ($object->meta->get_all_attributes) {
  my $name = $attr->name;

  next unless $attr->has_value($object);

  # Or, perhaps get_value(), depending on your requirements.
  say $attr->get_raw_value($object);
}
+4

All Articles