Class::...ttribute(3)
π Class::MOP::Attribute β Attribute Meta Object π
okay bestie, so this is Class::MOP::Attribute, and it lives in section 3 of the Perl docs β the user contributed Perl documentation zone, iykyk. It's the meta object that represents an attribute. Buckle up, it's a long one, but you're gonna slay it.
β¨ VERSION β¨
version 2.4000
πΈ SYNOPSIS πΈ
Class::MOP::Attribute->new(
foo => (
accessor => 'foo', # dual purpose get/set accessor
predicate => 'has_foo', # predicate check for defined-ness
init_arg => '-foo', # class->new will look for a -foo key
default => 'BAR IS BAZ!' # if no -foo key is provided, use this
)
);
Class::MOP::Attribute->new(
bar => (
reader => 'bar', # getter
writer => 'set_bar', # setter
predicate => 'has_bar', # predicate check for defined-ness
init_arg => ':bar', # class->new will look for a :bar key
# no default value means it is undef
)
);
π¦ DESCRIPTION π¦
So the Attribute Protocol? Almost entirely an invention of Class::MOP. Like, Perl 5 does not have a consistent notion of attributes, bestie. There are so many ways people do this, and honestly very few (if any) of them are easily discoverable by this module. It's giving chaos π.
That said, this module is on a mission to inject some order into all that chaos by introducing a consistent API that you can use to create object attributes. main character energy, honestly.
π METHODS π
π Creation π
Class::MOP::Attribute->new($name, ?%options)
An attribute must β at the absolute bare minimum β have a $name. Every other %options gets added as key-value pairs. That's the whole vibe.
init_argβ this is a string value representing the expected key in an initialization hash. So like, if we have aninit_argvalue of-foo, then this next bit of code will Just Workβ’:
MyClass->meta->new_object( -foo => 'Hello There' );
If an init_arg is not assigned, it will automatically use the attribute's name. And if init_arg is explicitly set to undef, then the attribute cannot be specified during initialization. periodt.
builderβ this provides the name of a method that will be called to initialize the attribute. That method gets called on the object after it is constructed. It's expected to return a valid value for the attribute.defaultβ you can use this to provide an explicit default for initializing the attribute. If the default you provide is a subroutine reference, then that reference will be called as a method on the object.
If the value is a simple scalar (string or number), then you can just pass it as is. But if you want to initialize it with a HASH or ARRAY ref, then you gotta wrap that inside a subroutine reference:
Class::MOP::Attribute->new(
'foo' => (
default => sub { [] },
)
);
# or ...
Class::MOP::Attribute->new(
'foo' => (
default => sub { {} },
)
);
If you want to initialize an attribute with a subroutine reference itself, then you need to wrap that in a subroutine too:
Class::MOP::Attribute->new(
'foo' => (
default => sub {
sub { print "Hello World" }
},
)
);
And lastly, if the value of your attribute is dependent upon some other aspect of the instance structure, then you can take advantage of the fact that the default value is called as a method:
Class::MOP::Attribute->new(
'object_identity' => (
default => sub { Scalar::Util::refaddr( $_[0] ) },
)
);
β οΈ heads up bestie: there is no guarantee that attributes are initialized in any particular order, so you cannot rely on the value of some other attribute when generating the default. fr fr, don't do it.
initializerβ this option can be either a method name or a subroutine reference. This method will be called when setting the attribute's value in the constructor. Unlikedefaultandbuilder, the initializer is only called when a value is provided to the constructor. The initializer lets you munge this value during object construction. β¨
The initializer is called as a method with three arguments. The first is the value that was passed to the constructor. The second is a subroutine reference that can be called to actually set the attribute's value, and the last is the associated Class::MOP::Attribute object.
This contrived example shows an initializer that sets the attribute to twice the given value:
Class::MOP::Attribute->new(
'doubled' => (
initializer => sub {
my ( $self, $value, $set, $attr ) = @_;
$set->( $value * 2 );
},
)
);
Since an initializer can be a method name, you can easily make attribute initialization use the writer:
Class::MOP::Attribute->new(
'some_attr' => (
writer => 'some_attr',
initializer => 'some_attr',
)
);
Your writer (actually, a wrapper around the writer, using method modifications) will need to examine @_ and determine under which context it is being called:
around 'some_attr' => sub {
my $orig = shift;
my $self = shift;
# $value is not defined if being called as a reader
# $setter and $attr are only defined if being called as an initializer
my ($value, $setter, $attr) = @_;
# the reader behaves normally
return $self->$orig if not @_;
# mutate $value as desired
# $value = <something($value);
# if called as an initializer, set the value and we're done
return $setter->($row) if $setter;
# otherwise, call the real writer with the new value
$self->$orig($row);
};
The accessor, reader, writer, predicate and clearer options all accept the same parameters, btw. You can provide the name of the method, in which case an appropriate default method will be generated for you. Or instead you can also provide a hash reference containing exactly one key (the method name) and one value. That value should be a subroutine reference, which will be installed as the method itself. iconic, honestly.
accessorβ anaccessoris a standard Perl-style read/write accessor. It will return the value of the attribute, and if a value is passed as an argument, it will assign that value to the attribute.
note thatundefis a legitimate value, so this will work:perl $object->set_something(undef);
readerβ this is a basic read-only accessor. It returns the value of the attribute.writerβ this is a basic write accessor, it accepts a single argument, and assigns that value to the attribute.
note thatundefis a legitimate value, so this will work:perl $object->set_something(undef);
predicateβ the predicate method returns a boolean indicating whether or not the attribute has been explicitly set.
note that the predicate returns true even if the attribute was set to a false value (0orundef). yes really, bestie. π
clearerβ this method will uninitialize the attribute. After an attribute is cleared, itspredicatewill return false.definition_contextβ mostly, this exists as a hook for the benefit of Moose.
This option should be a hash reference containing several keys which will be used when inlining the attribute's accessors. The keys should include line, the line number where the attribute was created, and either file or description.
This information will ultimately be used when eval'ing inlined accessor code so that error messages report a useful line and file name.
$attr->clone(%options)
This clones the attribute. Any options you provide will override the settings of the original attribute. You can change the name of the new attribute by passing a name key in %options. π¦
π Informational π
These are all basic read-only accessors for the values passed into the constructor.
$attr->name
Returns the attribute's name.
$attr->accessor / $attr->reader / $attr->writer / $attr->predicate / $attr->clearer
The accessor, reader, writer, predicate, and clearer methods all return exactly what was passed to the constructor, so it can be either a string containing a method name, or a hash reference.
$attr->initializer
Returns the initializer as passed to the constructor, so this may be either a method name or a subroutine reference.
$attr->init_arg / $attr->is_default_a_coderef / $attr->builder / $attr->default($instance)
The $instance argument is optional. If you don't pass it, the return value for this method is exactly what was passed to the constructor, either a simple scalar or a subroutine reference.
If you do pass an $instance and the default is a subroutine reference, then the reference is called as a method on the $instance and the generated value is returned. π
$attr->slots
Return a list of slots required by the attribute. This is usually just one, the name of the attribute.
A slot is the name of the hash key used to store the attribute in an object instance.
$attr->get_read_method/$attr->get_write_methodβ okay so these hand you the name of a method thatβs suitable for reading or writing the attributeβs value in the class itβs associated with. If the attribute is read-only or write-only, these can returnundefas appropriate. no cap.$attr->has_read_method/$attr->has_write_methodβ this returns a boolean that says whether the attribute has a named read or write method. slay.$attr->get_read_method_ref/$attr->get_write_method_refβ returns the subroutine reference of a method suitable for reading or writing the attributeβs value in the associated class. These methods always return a subroutine reference, regardless of whether the attribute is read-only or write-only. periodt.$attr->insertion_orderβ if this attribute has been inserted into a class, this returns a zero based index regarding the order of insertion. iykyk.
Informational predicates β¨
These are all basic predicate methods for the values passed into new.
$attr->has_accessor/$attr->has_reader/$attr->has_writer/$attr->has_predicate/$attr->has_clearer/$attr->has_initializer/$attr->has_init_argβ these are the basic predicate methods for the values passed intonew. Forhas_init_arg, this will be false if theinit_argwas set toundef. π$attr->has_defaultβ this will be false if thedefaultwas set toundef, sinceundefis the defaultdefaultanyway. not me side-eyeing that default. π$attr->has_builder/$attr->has_insertion_orderβ this will be false if this attribute has not be inserted into a class. (yes, βhas not beβ β we donβt make the rules, bestie). π
Value management π οΈ
These methods are basically βback doorsβ to the instance, and can be used to bypass the regular accessors, but still stay within the MOP.
These methods are not for general use, and should only be used if you really know what you are doing. seriously, bestie. π₯
$attr->initialize_instance_slot($meta_instance, $instance, $params)β this method is used internally to initialize the attributeβs slot in the object$instance. The$paramsis a hash reference of the values passed to the object constructor. Itβs unlikely that youβll need to call this method yourself. lowkey internal only. π ββοΈ$attr->set_value($instance, $value)β sets the value without going through the accessor. Note that this works even with read-only attributes. the audacity, honestly. π$attr->set_raw_value($instance, $value)β sets the value with no side effects such as a trigger. This doesnβt actually apply to Class::MOP attributes, only to subclasses. iykyk. β¨$attr->set_initial_value($instance, $value)β sets the value without going through the accessor. This method is only called when the instance is first being initialized. main character energy. π$attr->get_value($instance)β returns the value without going through the accessor. Note that this works even with write-only accessors. sneaky but iconic. π¦$attr->get_raw_value($instance)β returns the value without any side effects such as lazy attributes. Doesnβt actually apply to Class::MOP attributes, only to subclasses. fr fr. πΈ$attr->has_value($instance)β return a boolean indicating whether the attribute has been set in$instance. This how the defaultpredicatemethod works. (yes, βThis howβ β original typo stays. π)$attr->clear_value($instance)β this will clear the attributeβs value in$instance. This is what the defaultclearercalls. Note that this works even if the attribute does not have any associated read, write or clear methods. periodt. π§Ή
Class association π
These methods allow you to manage the attributes association with the class that contains it. These methods should not be used lightly, nor are they very magical, they are mostly used internally and by metaclass instances.
$attr->associated_classβ this returns theClass::MOP::Classwith which this attribute is associated, if any. π$attr->attach_to_class($metaclass)β this method stores a weakened reference to the$metaclassobject internally. This method does not remove the attribute from its old class, nor does it create any accessors in the new class. It is probably best to use theClass::MOP::Classadd_attributemethod instead. bestie, just useadd_attribute. π$attr->detach_from_classβ this method removes the associate metaclass object from the attribute it has one. This method does not remove the attribute itself from the class, or remove its accessors. It is probably best to use theClass::MOP::Classremove_attributemethod instead. again,remove_attributeis the move. π
Attribute Accessor generation βοΈ
$attr->accessor_metaclassβ accessor methods are generated using an accessor metaclass. By default, this isClass::MOP::Method::Accessor. This method returns the name of the accessor metaclass that this attribute uses. slay. β¨$attr->associate_method($method)β this associates aClass::MOP::Methodobject with the attribute. Typically, this is called internally when an attribute generates its accessors. π«Ά$attr->associated_methodsβ this returns the list of methods which have been associated with the attribute. π$attr->install_accessorsβ this method generates and installs code for the attributeβs accessors. It is typically called from theClass::MOP::Classadd_attributemethod. π»$attr->remove_accessorsβ this method removes all of the accessors associated with the attribute. This does not currently remove methods from the list returned byassociated_methods. (so the list is still there, lowkey messy but okay). π$attr->inline_get/$attr->inline_set/$attr->inline_has/$attr->inline_clearβ these methods return a code snippet suitable for inlining the relevant operation. They expect strings containing variable names to be used in the inlining, like'$self'or'$_[1]'. iykyk. π₯
Introspection π
Class::MOP::Attribute->metaβ this will return aClass::MOP::Classinstance for this class. It should also be noted thatClass::MOPwill actually bootstrap this module by installing a number of attribute meta-objects into its metaclass. meta. π€―
AUTHORS π«Ά
- Stevan Little <stevan@cpan.org>
- Dave Rolsky <autarch@urth.org>
- Jesse Luehrs <doy@cpan.org>
- Shawn M Moore <sartak@cpan.org>
- ΧΧΧΧ Χ§ΧΧ'ΧΧ (Yuval Kogman) <nothingmuch@woobling.org>
- Karen Etheridge <ether@cpan.org>
- Florian Ragwitz <rafl@debian.org>
- Hans Dieter Pearcey <hdp@cpan.org>
- Chris Prather <chris@prather.org>
- Matt S Trout <mstrout@cpan.org>
COPYRIGHT AND LICENSE π
This software is copyright (c) 2006 by Infinity Interactive, Inc.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
okay bestie, thatβs the whole vibe π this page is from perl v5.42.0, dated 2025-07-25, and itβs the Class::...ttribute(3) manpage. periodt. β¨
π¦ where this page comes from
- fedora 43: perl-Moose 2.4000-4.fc43 Β· GPL-1.0-or-later OR Artistic-1.0-Perl
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms