{
    "mode": "perldoc",
    "parameter": "Moose::Manual::Attributes",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Moose%3A%3AManual%3A%3AAttributes/json",
    "generated": "2026-06-09T17:52:53Z",
    "sections": {
        "NAME": {
            "content": "Moose::Manual::Attributes - Object attributes with Moose\n",
            "subsections": []
        },
        "VERSION": {
            "content": "version 2.2200\n",
            "subsections": []
        },
        "INTRODUCTION": {
            "content": "Moose attributes have many properties, and attributes are probably the single most powerful and\nflexible part of Moose. You can create a powerful class simply by declaring attributes. In fact,\nit's possible to have classes that consist solely of attribute declarations.\n\nAn attribute is a property that every member of a class has. For example, we might say that\n\"every \"Person\" object has a first name and last name\". Attributes can be optional, so that we\ncan say \"some \"Person\" objects have a social security number (and some don't)\".\n\nAt its simplest, an attribute can be thought of as a named value (as in a hash) that can be read\nand set. However, attributes can also have defaults, type constraints, delegation and much more.\n\nIn other languages, attributes are also referred to as slots or properties.\n",
            "subsections": []
        },
        "ATTRIBUTE OPTIONS": {
            "content": "Use the \"has\" function to declare an attribute:\n\npackage Person;\n\nuse Moose;\n\nhas 'firstname' => ( is => 'rw' );\n\nThis says that all \"Person\" objects have an optional read-write \"firstname\" attribute.\n",
            "subsections": [
                {
                    "name": "Read-write vs. read-only",
                    "content": "The options passed to \"has\" define the properties of the attribute. There are many options, but\nin the simplest form you just need to set \"is\", which can be either \"ro\" (read-only) or \"rw\"\n(read-write). When an attribute is \"rw\", you can change it by passing a value to its accessor.\nWhen an attribute is \"ro\", you may only read the current value of the attribute through its\naccessor. You can, however, set the attribute when creating the object by passing it to the\nconstructor.\n\nIn fact, you could even omit \"is\", but that gives you an attribute that has no accessor. This\ncan be useful with other attribute options, such as \"handles\". However, if your attribute\ngenerates *no* accessors, Moose will issue a warning, because that usually means the programmer\nforgot to say the attribute is read-only or read-write. If you really mean to have no accessors,\nyou can silence this warning by setting \"is\" to \"bare\".\n"
                },
                {
                    "name": "Accessor methods",
                    "content": "Each attribute has one or more accessor methods. An accessor lets you read and write the value\nof that attribute for an object.\n\nBy default, the accessor method has the same name as the attribute. If you declared your\nattribute as \"ro\" then your accessor will be read-only. If you declared it as \"rw\", you get a\nread-write accessor. Simple.\n\nGiven our \"Person\" example above, we now have a single \"firstname\" accessor that can read or\nwrite a \"Person\" object's \"firstname\" attribute's value.\n\nIf you want, you can also explicitly specify the method names to be used for reading and writing\nan attribute's value. This is particularly handy when you'd like an attribute to be publicly\nreadable, but only privately settable. For example:\n\nhas 'weight' => (\nis     => 'ro',\nwriter => 'setweight',\n);\n\nThis might be useful if weight is calculated based on other methods. For example, every time the\n\"eat\" method is called, we might adjust weight. This lets us hide the implementation details of\nweight changes, but still provide the weight value to users of the class.\n\nSome people might prefer to have distinct methods for reading and writing. In *Perl Best\nPractices*, Damian Conway recommends that reader methods start with \"get\" and writer methods\nstart with \"set\".\n\nWe can do exactly that by providing names for both the \"reader\" and \"writer\" methods:\n\nhas 'weight' => (\nis     => 'rw',\nreader => 'getweight',\nwriter => 'setweight',\n);\n\nIf you're thinking that doing this over and over would be insanely tedious, you're right!\nFortunately, Moose provides a powerful extension system that lets you override the default\nnaming conventions. See Moose::Manual::MooseX for more details.\n"
                },
                {
                    "name": "Predicate and clearer methods",
                    "content": "Moose allows you to explicitly distinguish between a false or undefined attribute value and an\nattribute which has not been set. If you want to access this information, you must define\nclearer and predicate methods for an attribute.\n\nA predicate method tells you whether or not a given attribute is currently set. Note that an\nattribute can be explicitly set to \"undef\" or some other false value, but the predicate will\nreturn true.\n\nThe clearer method unsets the attribute. This is *not* the same as setting the value to \"undef\",\nbut you can only distinguish between them if you define a predicate method!\n\nHere's some code to illustrate the relationship between an accessor, predicate, and clearer\nmethod.\n\npackage Person;\n\nuse Moose;\n\nhas 'ssn' => (\nis        => 'rw',\nclearer   => 'clearssn',\npredicate => 'hasssn',\n);\n\n...\n\nmy $person = Person->new();\n$person->hasssn; # false\n\n$person->ssn(undef);\n$person->ssn; # returns undef\n$person->hasssn; # true\n\n$person->clearssn;\n$person->ssn; # returns undef\n$person->hasssn; # false\n\n$person->ssn('123-45-6789');\n$person->ssn; # returns '123-45-6789'\n$person->hasssn; # true\n\nmy $person2 = Person->new( ssn => '111-22-3333');\n$person2->hasssn; # true\n\nBy default, Moose does not make a predicate or clearer for you. You must explicitly provide\nnames for them, and then Moose will create the methods for you.\n\nRequired or not?\nBy default, all attributes are optional, and do not need to be provided at object construction\ntime. If you want to make an attribute required, simply set the \"required\" option to true:\n\nhas 'name' => (\nis       => 'ro',\nrequired => 1,\n);\n\nThere are a couple caveats worth mentioning in regards to what \"required\" actually means.\n\nBasically, all it says is that this attribute (\"name\") must be provided to the constructor or it\nmust have either a default or a builder. It does not say anything about its value, so it could\nbe \"undef\".\n\nIf you define a clearer method on a required attribute, the clearer *will* work, so even a\nrequired attribute can be unset after object construction.\n\nThis means that if you do make an attribute required, providing a clearer doesn't make much\nsense. In some cases, it might be handy to have a *private* \"clearer\" and \"predicate\" for a\nrequired attribute.\n"
                },
                {
                    "name": "Default and builder methods",
                    "content": "Attributes can have default values, and Moose provides two ways to specify that default.\n\nIn the simplest form, you simply provide a non-reference scalar value for the \"default\" option:\n\nhas 'size' => (\nis        => 'ro',\ndefault   => 'medium',\npredicate => 'hassize',\n);\n\nIf the size attribute is not provided to the constructor, then it ends up being set to \"medium\":\n\nmy $person = Person->new();\n$person->size; # medium\n$person->hassize; # true\n\nYou can also provide a subroutine reference for \"default\". This reference will be called as a\nmethod on the object.\n\nhas 'size' => (\nis => 'ro',\ndefault =>\nsub { ( 'small', 'medium', 'large' )[ int( rand 3 ) ] },\npredicate => 'hassize',\n);\n\nThis is a trivial example, but it illustrates the point that the subroutine will be called for\nevery new object created.\n\nWhen you provide a \"default\" subroutine reference, it is called as a method on the object, with\nno additional parameters:\n\nhas 'size' => (\nis      => 'ro',\ndefault => sub {\nmy $self = shift;\n\nreturn $self->height > 200 ? 'large' : 'average';\n},\n);\n\nWhen the \"default\" is called during object construction, it may be called before other\nattributes have been set. If your default is dependent on other parts of the object's state, you\ncan make the attribute \"lazy\". Laziness is covered in the next section.\n\nIf you want to use a reference of any sort as the default value, you must return it from a\nsubroutine.\n\nhas 'mapping' => (\nis      => 'ro',\ndefault => sub { {} },\n);\n\nThis is necessary because otherwise Perl would instantiate the reference exactly once, and it\nwould be shared by all objects:\n\nhas 'mapping' => (\nis      => 'ro',\ndefault => {}, # wrong!\n);\n\nMoose will throw an error if you pass a bare non-subroutine reference as the default.\n\nIf Moose allowed this then the default mapping attribute could easily end up shared across many\nobjects. Instead, wrap it in a subroutine reference as we saw above.\n\nThis is a bit awkward, but it's just the way Perl works.\n\nAs an alternative to using a subroutine reference, you can supply a \"builder\" method for your\nattribute:\n\nhas 'size' => (\nis        => 'ro',\nbuilder   => 'buildsize',\npredicate => 'hassize',\n);\n\nsub buildsize {\nreturn ( 'small', 'medium', 'large' )[ int( rand 3 ) ];\n}\n\nThis has several advantages. First, it moves a chunk of code to its own named method, which\nimproves readability and code organization. Second, because this is a *named* method, it can be\nsubclassed or provided by a role.\n\nWe strongly recommend that you use a \"builder\" instead of a \"default\" for anything beyond the\nmost trivial default.\n\nA \"builder\", just like a \"default\", is called as a method on the object with no additional\nparameters.\n\nBuilders allow subclassing\nBecause the \"builder\" is called *by name*, it goes through Perl's method resolution. This means\nthat builder methods are both inheritable and overridable.\n\nIf we subclass our \"Person\" class, we can override \"buildsize\":\n\npackage Lilliputian;\n\nuse Moose;\nextends 'Person';\n\nsub buildsize { return 'small' }\n\nBuilders work well with roles\nBecause builders are called by name, they work well with roles. For example, a role could\nprovide an attribute but require that the consuming class provide the \"builder\":\n\npackage HasSize;\nuse Moose::Role;\n\nrequires 'buildsize';\n\nhas 'size' => (\nis      => 'ro',\nlazy    => 1,\nbuilder => 'buildsize',\n);\n\npackage Lilliputian;\nuse Moose;\n\nwith 'HasSize';\n\nsub buildsize { return 'small' }\n\nRoles are covered in Moose::Manual::Roles.\n"
                },
                {
                    "name": "Laziness",
                    "content": "Moose lets you defer attribute population by making an attribute \"lazy\":\n\nhas 'size' => (\nis      => 'ro',\nlazy    => 1,\nbuilder => 'buildsize',\n);\n\nWhen \"lazy\" is true, the default is not generated until the reader method is called, rather than\nat object construction time. There are several reasons you might choose to do this.\n\nFirst, if the default value for this attribute depends on some other attributes, then the\nattribute *must* be \"lazy\". During object construction, defaults are not generated in a\npredictable order, so you cannot count on some other attribute being populated when generating a\ndefault.\n\nSecond, there's often no reason to calculate a default before it's needed. Making an attribute\n\"lazy\" lets you defer the cost until the attribute is needed. If the attribute is *never*\nneeded, you save some CPU time.\n\nWe recommend that you make any attribute with a builder or non-trivial default \"lazy\" as a\nmatter of course.\n\nLazy defaults and $\nPlease note that a lazy default or builder can be called anywhere, even inside a \"map\" or\n\"grep\". This means that if your default sub or builder changes $, something weird could happen.\nYou can prevent this by adding \"local $\" inside your default or builder.\n\nConstructor parameters (\"initarg\")\nBy default, each attribute can be passed by name to the class's constructor. On occasion, you\nmay want to use a different name for the constructor parameter. You may also want to make an\nattribute unsettable via the constructor.\n\nYou can do either of these things with the \"initarg\" option:\n\nhas 'bigness' => (\nis       => 'ro',\ninitarg => 'size',\n);\n\nNow we have an attribute named \"bigness\", but we pass \"size\" to the constructor.\n\nEven more useful is the ability to disable setting an attribute via the constructor. This is\nparticularly handy for private attributes:\n\nhas 'geneticcode' => (\nis       => 'ro',\nlazy     => 1,\nbuilder  => 'buildgeneticcode',\ninitarg => undef,\n);\n\nBy setting the \"initarg\" to \"undef\", we make it impossible to set this attribute when creating\na new object.\n"
                },
                {
                    "name": "Weak references",
                    "content": "Moose has built-in support for weak references. If you set the \"weakref\" option to a true\nvalue, then it will call \"Scalar::Util::weaken\" whenever the attribute is set:\n\nhas 'parent' => (\nis       => 'rw',\nweakref => 1,\n);\n\n$node->parent($parentnode);\n\nThis is very useful when you're building objects that may contain circular references.\n\nWhen the object in a weak reference goes out of scope, the attribute's value will become \"undef\"\n\"behind the scenes\". This is done by the Perl interpreter directly, so Moose does not see this\nchange. This means that triggers don't fire, coercions aren't applied, etc.\n\nThe attribute is not cleared, so a predicate method for that attribute will still return true.\nSimilarly, when the attribute is next accessed, a default value will not be generated.\n"
                },
                {
                    "name": "Triggers",
                    "content": "A \"trigger\" is a subroutine that is called whenever the attribute is set:\n\nhas 'size' => (\nis      => 'rw',\ntrigger => \\&sizeset,\n);\n\nsub sizeset {\nmy ( $self, $size, $oldsize ) = @;\n\nmy $msg = $self->name;\n\nif ( @ > 2 ) {\n$msg .= \" - old size was $oldsize\";\n}\n\n$msg .= \" - size is now $size\";\nwarn $msg;\n}\n\nThe trigger is called *after* an attribute's value is set. It is called as a method on the\nobject, and receives the new and old values as its arguments. If the attribute had not\npreviously been set at all, then only the new value is passed. This lets you distinguish between\nthe case where the attribute had no value versus when the old value was \"undef\".\n\nThis differs from an \"after\" method modifier in two ways. First, a trigger is only called when\nthe attribute is set, as opposed to whenever the accessor method is called (for reading or\nwriting). Second, it is also called when an attribute's value is passed to the constructor.\n\nHowever, triggers are *not* called when an attribute is populated from a \"default\" or \"builder\".\n"
                },
                {
                    "name": "Attribute types",
                    "content": "Attributes can be restricted to only accept certain types:\n\nhas 'firstname' => (\nis  => 'ro',\nisa => 'Str',\n);\n\nThis says that the \"firstname\" attribute must be a string.\n\nMoose also provides a shortcut for specifying that an attribute only accepts objects that do a\ncertain role:\n\nhas 'weapon' => (\nis   => 'rw',\ndoes => 'MyApp::Weapon',\n);\n\nSee the Moose::Manual::Types documentation for a complete discussion of Moose's type system.\n"
                },
                {
                    "name": "Delegation",
                    "content": "An attribute can define methods which simply delegate to its value:\n\nhas 'haircolor' => (\nis      => 'ro',\nisa     => 'Graphics::Color::RGB',\nhandles => { haircolorhex => 'ashexstring' },\n);\n\nThis adds a new method, \"haircolorhex\". When someone calls \"haircolorhex\", internally, the\nobject just calls \"$self->haircolor->ashexstring\".\n\nSee Moose::Manual::Delegation for documentation on how to set up delegation methods.\n"
                },
                {
                    "name": "Attribute traits and metaclasses",
                    "content": "One of Moose's best features is that it can be extended in all sorts of ways through the use of\nmetaclass traits and custom metaclasses.\n\nYou can apply one or more traits to an attribute:\n\nuse MooseX::MetaDescription;\n\nhas 'size' => (\nis          => 'ro',\ntraits      => ['MooseX::MetaDescription::Meta::Trait'],\ndescription => {\nhtmlwidget  => 'textinput',\nserializeas => 'element',\n},\n);\n\nThe advantage of traits is that you can mix more than one of them together easily (in fact, a\ntrait is just a role under the hood).\n\nThere are a number of MooseX modules on CPAN which provide useful attribute metaclasses and\ntraits. See Moose::Manual::MooseX for some examples. You can also write your own metaclasses and\ntraits. See the \"Meta\" and \"Extending\" recipes in Moose::Cookbook for examples.\n"
                },
                {
                    "name": "Native Delegations",
                    "content": "Native delegations allow you to delegate to standard Perl data structures as if they were\nobjects.\n\nFor example, we can pretend that an array reference has methods like \"push()\", \"shift()\",\n\"map()\", \"count()\", and more.\n\nhas 'options' => (\ntraits  => ['Array'],\nis      => 'ro',\nisa     => 'ArrayRef[Str]',\ndefault => sub { [] },\nhandles => {\nalloptions    => 'elements',\naddoption     => 'push',\nmapoptions    => 'map',\noptioncount   => 'count',\nsortedoptions => 'sort',\n},\n);\n\nSee Moose::Manual::Delegation for more details.\n"
                }
            ]
        },
        "ATTRIBUTE INHERITANCE": {
            "content": "By default, a child inherits all of its parent class(es)' attributes as-is. However, you can\nchange most aspects of the inherited attribute in the child class. You cannot change any of its\nassociated method names (reader, writer, predicate, etc).\n\nTo change some aspects of an attribute, you simply prepend a plus sign (\"+\") to its name:\n\npackage LazyPerson;\n\nuse Moose;\n\nextends 'Person';\n\nhas '+firstname' => (\nlazy    => 1,\ndefault => 'Bill',\n);\n\nNow the \"firstname\" attribute in \"LazyPerson\" is lazy, and defaults to 'Bill'.\n\nWe recommend that you exercise caution when changing the type (\"isa\") of an inherited attribute.\n",
            "subsections": [
                {
                    "name": "Attribute Inheritance and Method Modifiers",
                    "content": "When an inherited attribute is defined, that creates an entirely new set of accessors for the\nattribute (reader, writer, predicate, etc.). This is necessary because these may be what was\nchanged when inheriting the attribute.\n\nAs a consequence, any method modifiers defined on the attribute's accessors in an ancestor class\nwill effectively be ignored, because the new accessors live in the child class and do not see\nthe modifiers from the parent class.\n"
                }
            ]
        },
        "MULTIPLE ATTRIBUTE SHORTCUTS": {
            "content": "If you have a number of attributes that differ only by name, you can declare them all at once:\n\npackage Point;\n\nuse Moose;\n\nhas [ 'x', 'y' ] => ( is => 'ro', isa => 'Int' );\n\nAlso, because \"has\" is just a function call, you can call it in a loop:\n\nfor my $name ( qw( x y ) ) {\nmy $builder = 'build' . $name;\nhas $name => ( is => 'ro', isa => 'Int', builder => $builder );\n}\n",
            "subsections": []
        },
        "MORE ON ATTRIBUTES": {
            "content": "Moose attributes are a big topic, and this document glosses over a few aspects. We recommend\nthat you read the Moose::Manual::Delegation and Moose::Manual::Types documents to get a more\ncomplete understanding of attribute features.\n",
            "subsections": []
        },
        "A FEW MORE OPTIONS": {
            "content": "Moose has lots of attribute options. The ones listed below are superseded by some more modern\nfeatures, but are covered for the sake of completeness.\n\nThe \"documentation\" option\nYou can provide a piece of documentation as a string for an attribute:\n\nhas 'firstname' => (\nis            => 'rw',\ndocumentation => q{The person's first (personal) name},\n);\n\nMoose does absolutely nothing with this information other than store it.\n\nThe \"autoderef\" option\nIf your attribute is an array reference or hash reference, the \"autoderef\" option will make\nMoose dereference the value when it is returned from the reader method *in list context*:\n\nmy %map = $object->mapping;\n\nThis option only works if your attribute is explicitly typed as an \"ArrayRef\" or \"HashRef\". When\nthe reader is called in *scalar* context, the reference itself is returned.\n\nHowever, we recommend that you use Moose::Meta::Attribute::Native traits for these types of\nattributes, which gives you much more control over how they are accessed and manipulated. See\nalso \"Use Moose::Meta::Attribute::Native traits instead of auto deref\" in\nMoose::Manual::BestPractices.\n",
            "subsections": [
                {
                    "name": "Initializer",
                    "content": "Moose provides an attribute option called \"initializer\". This is called when the attribute's\nvalue is being set in the constructor, and lets you change the value before it is set.\n"
                }
            ]
        },
        "AUTHORS": {
            "content": "*   Stevan Little <stevan@cpan.org>\n\n*   Dave Rolsky <autarch@urth.org>\n\n*   Jesse Luehrs <doy@cpan.org>\n\n*   Shawn M Moore <sartak@cpan.org>\n\n*   יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org>\n\n*   Karen Etheridge <ether@cpan.org>\n\n*   Florian Ragwitz <rafl@debian.org>\n\n*   Hans Dieter Pearcey <hdp@cpan.org>\n\n*   Chris Prather <chris@prather.org>\n\n*   Matt S Trout <mstrout@cpan.org>\n",
            "subsections": []
        },
        "COPYRIGHT AND LICENSE": {
            "content": "This software is copyright (c) 2006 by Infinity Interactive, Inc.\n\nThis is free software; you can redistribute it and/or modify it under the same terms as the Perl\n5 programming language system itself.\n",
            "subsections": []
        }
    },
    "summary": "Moose::Manual::Attributes - Object attributes with Moose",
    "flags": [],
    "examples": [],
    "see_also": []
}