{
    "mode": "man",
    "parameter": "perlobj",
    "section": "1",
    "url": "https://www.chedong.com/phpMan.php/man/perlobj/1/json",
    "generated": "2026-06-13T21:19:57Z",
    "sections": {
        "NAME": {
            "content": "perlobj - Perl object reference\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This document provides a reference for Perl's object orientation features. If you're looking\nfor an introduction to object-oriented programming in Perl, please see perlootut.\n\nIn order to understand Perl objects, you first need to understand references in Perl. See\nperlreftut for details.\n\nThis document describes all of Perl's object-oriented (OO) features from the ground up. If\nyou're just looking to write some object-oriented code of your own, you are probably better\nserved by using one of the object systems from CPAN described in perlootut.\n\nIf you're looking to write your own object system, or you need to maintain code which\nimplements objects from scratch then this document will help you understand exactly how Perl\ndoes object orientation.\n\nThere are a few basic principles which define object oriented Perl:\n\n1.  An object is simply a data structure that knows to which class it belongs.\n\n2.  A class is simply a package. A class provides methods that expect to operate on objects.\n\n3.  A method is simply a subroutine that expects a reference to an object (or a package name,\nfor class methods) as the first argument.\n\nLet's look at each of these principles in depth.\n",
            "subsections": [
                {
                    "name": "An Object is Simply a Data Structure",
                    "content": "Unlike many other languages which support object orientation, Perl does not provide any\nspecial syntax for constructing an object. Objects are merely Perl data structures (hashes,\narrays, scalars, filehandles, etc.) that have been explicitly associated with a particular\nclass.\n\nThat explicit association is created by the built-in \"bless\" function, which is typically\nused within the constructor subroutine of the class.\n\nHere is a simple constructor:\n\npackage File;\n\nsub new {\nmy $class = shift;\n\nreturn bless {}, $class;\n}\n\nThe name \"new\" isn't special. We could name our constructor something else:\n\npackage File;\n\nsub load {\nmy $class = shift;\n\nreturn bless {}, $class;\n}\n\nThe modern convention for OO modules is to always use \"new\" as the name for the constructor,\nbut there is no requirement to do so. Any subroutine that blesses a data structure into a\nclass is a valid constructor in Perl.\n\nIn the previous examples, the \"{}\" code creates a reference to an empty anonymous hash. The\n\"bless\" function then takes that reference and associates the hash with the class in $class.\nIn the simplest case, the $class variable will end up containing the string \"File\".\n\nWe can also use a variable to store a reference to the data structure that is being blessed\nas our object:\n\nsub new {\nmy $class = shift;\n\nmy $self = {};\nbless $self, $class;\n\nreturn $self;\n}\n\nOnce we've blessed the hash referred to by $self we can start calling methods on it. This is\nuseful if you want to put object initialization in its own separate method:\n\nsub new {\nmy $class = shift;\n\nmy $self = {};\nbless $self, $class;\n\n$self->initialize();\n\nreturn $self;\n}\n\nSince the object is also a hash, you can treat it as one, using it to store data associated\nwith the object. Typically, code inside the class can treat the hash as an accessible data\nstructure, while code outside the class should always treat the object as opaque. This is\ncalled encapsulation. Encapsulation means that the user of an object does not have to know\nhow it is implemented. The user simply calls documented methods on the object.\n\nNote, however, that (unlike most other OO languages) Perl does not ensure or enforce\nencapsulation in any way. If you want objects to actually be opaque you need to arrange for\nthat yourself. This can be done in a variety of ways, including using \"Inside-Out objects\" or\nmodules from CPAN.\n\nObjects Are Blessed; Variables Are Not\n\nWhen we bless something, we are not blessing the variable which contains a reference to that\nthing, nor are we blessing the reference that the variable stores; we are blessing the thing\nthat the variable refers to (sometimes known as the referent). This is best demonstrated with\nthis code:\n\nuse Scalar::Util 'blessed';\n\nmy $foo = {};\nmy $bar = $foo;\n\nbless $foo, 'Class';\nprint blessed( $bar ) // 'not blessed';    # prints \"Class\"\n\n$bar = \"some other value\";\nprint blessed( $bar ) // 'not blessed';    # prints \"not blessed\"\n\nWhen we call \"bless\" on a variable, we are actually blessing the underlying data structure\nthat the variable refers to. We are not blessing the reference itself, nor the variable that\ncontains that reference. That's why the second call to \"blessed( $bar )\" returns false. At\nthat point $bar is no longer storing a reference to an object.\n\nYou will sometimes see older books or documentation mention \"blessing a reference\" or\ndescribe an object as a \"blessed reference\", but this is incorrect. It isn't the reference\nthat is blessed as an object; it's the thing the reference refers to (i.e. the referent).\n"
                },
                {
                    "name": "A Class is Simply a Package",
                    "content": "Perl does not provide any special syntax for class definitions. A package is simply a\nnamespace containing variables and subroutines. The only difference is that in a class, the\nsubroutines may expect a reference to an object or the name of a class as the first argument.\nThis is purely a matter of convention, so a class may contain both methods and subroutines\nwhich don't operate on an object or class.\n\nEach package contains a special array called @ISA. The @ISA array contains a list of that\nclass's parent classes, if any. This array is examined when Perl does method resolution,\nwhich we will cover later.\n\nCalling methods from a package means it must be loaded, of course, so you will often want to\nload a module and add it to @ISA at the same time. You can do so in a single step using the\nparent pragma.  (In older code you may encounter the base pragma, which is nowadays\ndiscouraged except when you have to work with the equally discouraged fields pragma.)\n\nHowever the parent classes are set, the package's @ISA variable will contain a list of those\nparents. This is simply a list of scalars, each of which is a string that corresponds to a\npackage name.\n\nAll classes inherit from the UNIVERSAL class implicitly. The UNIVERSAL class is implemented\nby the Perl core, and provides several default methods, such as \"isa()\", \"can()\", and\n\"VERSION()\".  The \"UNIVERSAL\" class will never appear in a package's @ISA variable.\n\nPerl only provides method inheritance as a built-in feature.  Attribute inheritance is left\nup the class to implement. See the \"Writing Accessors\" section for details.\n"
                },
                {
                    "name": "A Method is Simply a Subroutine",
                    "content": "Perl does not provide any special syntax for defining a method. A method is simply a regular\nsubroutine, and is declared with \"sub\".  What makes a method special is that it expects to\nreceive either an object or a class name as its first argument.\n\nPerl does provide special syntax for method invocation, the \"->\" operator. We will cover this\nin more detail later.\n\nMost methods you write will expect to operate on objects:\n\nsub save {\nmy $self = shift;\n\nopen my $fh, '>', $self->path() or die $!;\nprint {$fh} $self->data()       or die $!;\nclose $fh                       or die $!;\n}\n"
                },
                {
                    "name": "Method Invocation",
                    "content": "Calling a method on an object is written as \"$object->method\".\n\nThe left hand side of the method invocation (or arrow) operator is the object (or class\nname), and the right hand side is the method name.\n\nmy $pod = File->new( 'perlobj.pod', $data );\n$pod->save();\n\nThe \"->\" syntax is also used when dereferencing a reference. It looks like the same operator,\nbut these are two different operations.\n\nWhen you call a method, the thing on the left side of the arrow is passed as the first\nargument to the method. That means when we call \"Critter->new()\", the \"new()\" method receives\nthe string \"Critter\" as its first argument. When we call \"$fred->speak()\", the $fred variable\nis passed as the first argument to \"speak()\".\n\nJust as with any Perl subroutine, all of the arguments passed in @ are aliases to the\noriginal argument. This includes the object itself.  If you assign directly to $[0] you will\nchange the contents of the variable that holds the reference to the object. We recommend that\nyou don't do this unless you know exactly what you're doing.\n\nPerl knows what package the method is in by looking at the left side of the arrow. If the\nleft hand side is a package name, it looks for the method in that package. If the left hand\nside is an object, then Perl looks for the method in the package that the object has been\nblessed into.\n\nIf the left hand side is neither a package name nor an object, then the method call will\ncause an error, but see the section on \"Method Call Variations\" for more nuances.\n"
                },
                {
                    "name": "Inheritance",
                    "content": "We already talked about the special @ISA array and the parent pragma.\n\nWhen a class inherits from another class, any methods defined in the parent class are\navailable to the child class. If you attempt to call a method on an object that isn't defined\nin its own class, Perl will also look for that method in any parent classes it may have.\n\npackage File::MP3;\nuse parent 'File';    # sets @File::MP3::ISA = ('File');\n\nmy $mp3 = File::MP3->new( 'Andvari.mp3', $data );\n$mp3->save();\n\nSince we didn't define a \"save()\" method in the \"File::MP3\" class, Perl will look at the\n\"File::MP3\" class's parent classes to find the \"save()\" method. If Perl cannot find a\n\"save()\" method anywhere in the inheritance hierarchy, it will die.\n\nIn this case, it finds a \"save()\" method in the \"File\" class. Note that the object passed to\n\"save()\" in this case is still a \"File::MP3\" object, even though the method is found in the\n\"File\" class.\n\nWe can override a parent's method in a child class. When we do so, we can still call the\nparent class's method with the \"SUPER\" pseudo-class.\n\nsub save {\nmy $self = shift;\n\nsay 'Prepare to rock';\n$self->SUPER::save();\n}\n\nThe \"SUPER\" modifier can only be used for method calls. You can't use it for regular\nsubroutine calls or class methods:\n\nSUPER::save($thing);     # FAIL: looks for save() sub in package SUPER\n\nSUPER->save($thing);     # FAIL: looks for save() method in class\n#       SUPER\n\n$thing->SUPER::save();   # Okay: looks for save() method in parent\n#       classes\n\nHow SUPER is Resolved\n\nThe \"SUPER\" pseudo-class is resolved from the package where the call is made. It is not\nresolved based on the object's class. This is important, because it lets methods at different\nlevels within a deep inheritance hierarchy each correctly call their respective parent\nmethods.\n\npackage A;\n\nsub new {\nreturn bless {}, shift;\n}\n\nsub speak {\nmy $self = shift;\n\nsay 'A';\n}\n\npackage B;\n\nuse parent -norequire, 'A';\n\nsub speak {\nmy $self = shift;\n\n$self->SUPER::speak();\n\nsay 'B';\n}\n\npackage C;\n\nuse parent -norequire, 'B';\n\nsub speak {\nmy $self = shift;\n\n$self->SUPER::speak();\n\nsay 'C';\n}\n\nmy $c = C->new();\n$c->speak();\n\nIn this example, we will get the following output:\n\nA\nB\nC\n\nThis demonstrates how \"SUPER\" is resolved. Even though the object is blessed into the \"C\"\nclass, the \"speak()\" method in the \"B\" class can still call \"SUPER::speak()\" and expect it to\ncorrectly look in the parent class of \"B\" (i.e the class the method call is in), not in the\nparent class of \"C\" (i.e. the class the object belongs to).\n\nThere are rare cases where this package-based resolution can be a problem. If you copy a\nsubroutine from one package to another, \"SUPER\" resolution will be done based on the original\npackage.\n\nMultiple Inheritance\n\nMultiple inheritance often indicates a design problem, but Perl always gives you enough rope\nto hang yourself with if you ask for it.\n\nTo declare multiple parents, you simply need to pass multiple class names to \"use parent\":\n\npackage MultiChild;\n\nuse parent 'Parent1', 'Parent2';\n\nMethod Resolution Order\n\nMethod resolution order only matters in the case of multiple inheritance. In the case of\nsingle inheritance, Perl simply looks up the inheritance chain to find a method:\n\nGrandparent\n|\nParent\n|\nChild\n\nIf we call a method on a \"Child\" object and that method is not defined in the \"Child\" class,\nPerl will look for that method in the \"Parent\" class and then, if necessary, in the\n\"Grandparent\" class.\n\nIf Perl cannot find the method in any of these classes, it will die with an error message.\n\nWhen a class has multiple parents, the method lookup order becomes more complicated.\n\nBy default, Perl does a depth-first left-to-right search for a method.  That means it starts\nwith the first parent in the @ISA array, and then searches all of its parents, grandparents,\netc. If it fails to find the method, it then goes to the next parent in the original class's\n@ISA array and searches from there.\n\nSharedGreatGrandParent\n/                    \\\nPaternalGrandparent       MaternalGrandparent\n\\                    /\nFather        Mother\n\\      /\nChild\n\nSo given the diagram above, Perl will search \"Child\", \"Father\", \"PaternalGrandparent\",\n\"SharedGreatGrandParent\", \"Mother\", and finally \"MaternalGrandparent\". This may be a problem\nbecause now we're looking in \"SharedGreatGrandParent\" before we've checked all its derived\nclasses (i.e. before we tried \"Mother\" and \"MaternalGrandparent\").\n\nIt is possible to ask for a different method resolution order with the mro pragma.\n\npackage Child;\n\nuse mro 'c3';\nuse parent 'Father', 'Mother';\n\nThis pragma lets you switch to the \"C3\" resolution order. In simple terms, \"C3\" order ensures\nthat shared parent classes are never searched before child classes, so Perl will now search:\n\"Child\", \"Father\", \"PaternalGrandparent\", \"Mother\" \"MaternalGrandparent\", and finally\n\"SharedGreatGrandParent\". Note however that this is not \"breadth-first\" searching: All the\n\"Father\" ancestors (except the common ancestor) are searched before any of the \"Mother\"\nancestors are considered.\n\nThe C3 order also lets you call methods in sibling classes with the \"next\" pseudo-class. See\nthe mro documentation for more details on this feature.\n\nMethod Resolution Caching\n\nWhen Perl searches for a method, it caches the lookup so that future calls to the method do\nnot need to search for it again. Changing a class's parent class or adding subroutines to a\nclass will invalidate the cache for that class.\n\nThe mro pragma provides some functions for manipulating the method cache directly.\n"
                },
                {
                    "name": "Writing Constructors",
                    "content": "As we mentioned earlier, Perl provides no special constructor syntax.  This means that a\nclass must implement its own constructor. A constructor is simply a class method that returns\na reference to a new object.\n\nThe constructor can also accept additional parameters that define the object. Let's write a\nreal constructor for the \"File\" class we used earlier:\n\npackage File;\n\nsub new {\nmy $class = shift;\nmy ( $path, $data ) = @;\n\nmy $self = bless {\npath => $path,\ndata => $data,\n}, $class;\n\nreturn $self;\n}\n\nAs you can see, we've stored the path and file data in the object itself. Remember, under the\nhood, this object is still just a hash.  Later, we'll write accessors to manipulate this\ndata.\n\nFor our \"File::MP3\" class, we can check to make sure that the path we're given ends with\n\".mp3\":\n\npackage File::MP3;\n\nsub new {\nmy $class = shift;\nmy ( $path, $data ) = @;\n\ndie \"You cannot create a File::MP3 without an mp3 extension\\n\"\nunless $path =~ /\\.mp3\\z/;\n\nreturn $class->SUPER::new(@);\n}\n\nThis constructor lets its parent class do the actual object construction.\n"
                },
                {
                    "name": "Attributes",
                    "content": "An attribute is a piece of data belonging to a particular object.  Unlike most object-\noriented languages, Perl provides no special syntax or support for declaring and manipulating\nattributes.\n\nAttributes are often stored in the object itself. For example, if the object is an anonymous\nhash, we can store the attribute values in the hash using the attribute name as the key.\n\nWhile it's possible to refer directly to these hash keys outside of the class, it's\nconsidered a best practice to wrap all access to the attribute with accessor methods.\n\nThis has several advantages. Accessors make it easier to change the implementation of an\nobject later while still preserving the original API.\n\nAn accessor lets you add additional code around attribute access. For example, you could\napply a default to an attribute that wasn't set in the constructor, or you could validate\nthat a new value for the attribute is acceptable.\n\nFinally, using accessors makes inheritance much simpler. Subclasses can use the accessors\nrather than having to know how a parent class is implemented internally.\n\nWriting Accessors\n\nAs with constructors, Perl provides no special accessor declaration syntax, so classes must\nprovide explicitly written accessor methods.  There are two common types of accessors, read-\nonly and read-write.\n\nA simple read-only accessor simply gets the value of a single attribute:\n\nsub path {\nmy $self = shift;\n\nreturn $self->{path};\n}\n\nA read-write accessor will allow the caller to set the value as well as get it:\n\nsub path {\nmy $self = shift;\n\nif (@) {\n$self->{path} = shift;\n}\n\nreturn $self->{path};\n}\n"
                },
                {
                    "name": "An Aside About Smarter and Safer Code",
                    "content": "Our constructor and accessors are not very smart. They don't check that a $path is defined,\nnor do they check that a $path is a valid filesystem path.\n\nDoing these checks by hand can quickly become tedious. Writing a bunch of accessors by hand\nis also incredibly tedious. There are a lot of modules on CPAN that can help you write safer\nand more concise code, including the modules we recommend in perlootut.\n"
                },
                {
                    "name": "Method Call Variations",
                    "content": "Perl supports several other ways to call methods besides the \"$object->method()\" usage we've\nseen so far.\n\nMethod Names with a Fully Qualified Name\n\nPerl allows you to call methods using their fully qualified name (the package and method\nname):\n\nmy $mp3 = File::MP3->new( 'Regin.mp3', $data );\n$mp3->File::save();\n\nWhen you call a fully qualified method name like \"File::save\", the method resolution search\nfor the \"save\" method starts in the \"File\" class, skipping any \"save\" method the \"File::MP3\"\nclass may have defined. It still searches the \"File\" class's parents if necessary.\n\nWhile this feature is most commonly used to explicitly call methods inherited from an\nancestor class, there is no technical restriction that enforces this:\n\nmy $obj = Tree->new();\n$obj->Dog::bark();\n\nThis calls the \"bark\" method from class \"Dog\" on an object of class \"Tree\", even if the two\nclasses are completely unrelated. Use this with great care.\n\nThe \"SUPER\" pseudo-class that was described earlier is not the same as calling a method with\na fully-qualified name. See the earlier \"Inheritance\" section for details.\n\nMethod Names as Strings\n\nPerl lets you use a scalar variable containing a string as a method name:\n\nmy $file = File->new( $path, $data );\n\nmy $method = 'save';\n$file->$method();\n\nThis works exactly like calling \"$file->save()\". This can be very useful for writing dynamic\ncode. For example, it allows you to pass a method name to be called as a parameter to another\nmethod.\n\nClass Names as Strings\n\nPerl also lets you use a scalar containing a string as a class name:\n\nmy $class = 'File';\n\nmy $file = $class->new( $path, $data );\n\nAgain, this allows for very dynamic code.\n\nSubroutine References as Methods\n\nYou can also use a subroutine reference as a method:\n\nmy $sub = sub {\nmy $self = shift;\n\n$self->save();\n};\n\n$file->$sub();\n\nThis is exactly equivalent to writing \"$sub->($file)\". You may see this idiom in the wild\ncombined with a call to \"can\":\n\nif ( my $meth = $object->can('foo') ) {\n$object->$meth();\n}\n\nDereferencing Method Call\n\nPerl also lets you use a dereferenced scalar reference in a method call. That's a mouthful,\nso let's look at some code:\n\n$file->${ \\'save' };\n$file->${ returnsscalarref() };\n$file->${ \\( returnsscalar() ) };\n$file->${ returnsreftosubref() };\n\nThis works if the dereference produces a string or a subroutine reference.\n\nMethod Calls on Filehandles\n\nUnder the hood, Perl filehandles are instances of the \"IO::Handle\" or \"IO::File\" class. Once\nyou have an open filehandle, you can call methods on it. Additionally, you can call methods\non the \"STDIN\", \"STDOUT\", and \"STDERR\" filehandles.\n\nopen my $fh, '>', 'path/to/file';\n$fh->autoflush();\n$fh->print('content');\n\nSTDOUT->autoflush();\n"
                },
                {
                    "name": "Invoking Class Methods",
                    "content": "Because Perl allows you to use barewords for package names and subroutine names, it sometimes\ninterprets a bareword's meaning incorrectly. For example, the construct \"Class->new()\" can be\ninterpreted as either \"'Class'->new()\" or \"Class()->new()\".  In English, that second\ninterpretation reads as \"call a subroutine named Class(), then call new() as a method on the\nreturn value of Class()\". If there is a subroutine named \"Class()\" in the current namespace,\nPerl will always interpret \"Class->new()\" as the second alternative: a call to \"new()\" on the\nobject  returned by a call to \"Class()\"\n\nYou can force Perl to use the first interpretation (i.e. as a method call on the class named\n\"Class\") in two ways. First, you can append a \"::\" to the class name:\n\nClass::->new()\n\nPerl will always interpret this as a method call.\n\nAlternatively, you can quote the class name:\n\n'Class'->new()\n\nOf course, if the class name is in a scalar Perl will do the right thing as well:\n\nmy $class = 'Class';\n$class->new();\n\nIndirect Object Syntax\n"
                },
                {
                    "name": "Outside of the file handle case, use of this syntax is discouraged as it can confuse the Perl",
                    "content": ""
                },
                {
                    "name": "interpreter. See below for more details.",
                    "content": "Perl supports another method invocation syntax called \"indirect object\" notation. This syntax\nis called \"indirect\" because the method comes before the object it is being invoked on.\n\nThis syntax can be used with any class or object method:\n\nmy $file = new File $path, $data;\nsave $file;\n\nWe recommend that you avoid this syntax, for several reasons.\n\nFirst, it can be confusing to read. In the above example, it's not clear if \"save\" is a\nmethod provided by the \"File\" class or simply a subroutine that expects a file object as its\nfirst argument.\n\nWhen used with class methods, the problem is even worse. Because Perl allows subroutine names\nto be written as barewords, Perl has to guess whether the bareword after the method is a\nclass name or subroutine name. In other words, Perl can resolve the syntax as either\n\"File->new( $path, $data )\" or \"new( File( $path, $data ) )\".\n\nTo parse this code, Perl uses a heuristic based on what package names it has seen, what\nsubroutines exist in the current package, what barewords it has previously seen, and other\ninput. Needless to say, heuristics can produce very surprising results!\n\nOlder documentation (and some CPAN modules) encouraged this syntax, particularly for\nconstructors, so you may still find it in the wild.  However, we encourage you to avoid using\nit in new code.\n\nYou can force Perl to interpret the bareword as a class name by appending \"::\" to it, like we\nsaw earlier:\n\nmy $file = new File:: $path, $data;\n"
                },
                {
                    "name": "\"bless\", \"blessed\", and \"ref\"",
                    "content": "As we saw earlier, an object is simply a data structure that has been blessed into a class\nvia the \"bless\" function. The \"bless\" function can take either one or two arguments:\n\nmy $object = bless {}, $class;\nmy $object = bless {};\n\nIn the first form, the anonymous hash is being blessed into the class in $class. In the\nsecond form, the anonymous hash is blessed into the current package.\n\nThe second form is strongly discouraged, because it breaks the ability of a subclass to reuse\nthe parent's constructor, but you may still run across it in existing code.\n\nIf you want to know whether a particular scalar refers to an object, you can use the\n\"blessed\" function exported by Scalar::Util, which is shipped with the Perl core.\n\nuse Scalar::Util 'blessed';\n\nif ( defined blessed($thing) ) { ... }\n\nIf $thing refers to an object, then this function returns the name of the package the object\nhas been blessed into. If $thing doesn't contain a reference to a blessed object, the\n\"blessed\" function returns \"undef\".\n\nNote that \"blessed($thing)\" will also return false if $thing has been blessed into a class\nnamed \"0\". This is a possible, but quite pathological. Don't create a class named \"0\" unless\nyou know what you're doing.\n\nSimilarly, Perl's built-in \"ref\" function treats a reference to a blessed object specially.\nIf you call \"ref($thing)\" and $thing holds a reference to an object, it will return the name\nof the class that the object has been blessed into.\n\nIf you simply want to check that a variable contains an object reference, we recommend that\nyou use \"defined blessed($object)\", since \"ref\" returns true values for all references, not\njust objects.\n"
                },
                {
                    "name": "The UNIVERSAL Class",
                    "content": "All classes automatically inherit from the UNIVERSAL class, which is built-in to the Perl\ncore. This class provides a number of methods, all of which can be called on either a class\nor an object. You can also choose to override some of these methods in your class. If you do\nso, we recommend that you follow the built-in semantics described below.\n\nisa($class)\nThe \"isa\" method returns true if the object is a member of the class in $class, or a\nmember of a subclass of $class.\n\nIf you override this method, it should never throw an exception.\n\nDOES($role)\nThe \"DOES\" method returns true if its object claims to perform the role $role. By\ndefault, this is equivalent to \"isa\". This method is provided for use by object system\nextensions that implement roles, like \"Moose\" and \"Role::Tiny\".\n\nYou can also override \"DOES\" directly in your own classes. If you override this method,\nit should never throw an exception.\n\ncan($method)\nThe \"can\" method checks to see if the class or object it was called on has a method named\n$method. This checks for the method in the class and all of its parents. If the method\nexists, then a reference to the subroutine is returned. If it does not then \"undef\" is\nreturned.\n\nIf your class responds to method calls via \"AUTOLOAD\", you may want to overload \"can\" to\nreturn a subroutine reference for methods which your \"AUTOLOAD\" method handles.\n\nIf you override this method, it should never throw an exception.\n\nVERSION($need)\nThe \"VERSION\" method returns the version number of the class (package).\n\nIf the $need argument is given then it will check that the current version (as defined by\nthe $VERSION variable in the package) is greater than or equal to $need; it will die if\nthis is not the case. This method is called automatically by the \"VERSION\" form of \"use\".\n\nuse Package 1.2 qw(some imported subs);\n# implies:\nPackage->VERSION(1.2);\n\nWe recommend that you use this method to access another package's version, rather than\nlooking directly at $Package::VERSION. The package you are looking at could have\noverridden the \"VERSION\" method.\n\nWe also recommend using this method to check whether a module has a sufficient version.\nThe internal implementation uses the version module to make sure that different types of\nversion numbers are compared correctly.\n\nAUTOLOAD\nIf you call a method that doesn't exist in a class, Perl will throw an error. However, if\nthat class or any of its parent classes defines an \"AUTOLOAD\" method, that \"AUTOLOAD\" method\nis called instead.\n\n\"AUTOLOAD\" is called as a regular method, and the caller will not know the difference.\nWhatever value your \"AUTOLOAD\" method returns is returned to the caller.\n\nThe fully qualified method name that was called is available in the $AUTOLOAD package global\nfor your class. Since this is a global, if you want to refer to do it without a package name\nprefix under \"strict 'vars'\", you need to declare it.\n\n# XXX - this is a terrible way to implement accessors, but it makes\n# for a simple example.\nour $AUTOLOAD;\nsub AUTOLOAD {\nmy $self = shift;\n\n# Remove qualifier from original method name...\nmy $called =  $AUTOLOAD =~ s/.*:://r;\n\n# Is there an attribute of that name?\ndie \"No such attribute: $called\"\nunless exists $self->{$called};\n\n# If so, return it...\nreturn $self->{$called};\n}\n\nsub DESTROY { } # see below\n\nWithout the \"our $AUTOLOAD\" declaration, this code will not compile under the strict pragma.\n\nAs the comment says, this is not a good way to implement accessors.  It's slow and too clever\nby far. However, you may see this as a way to provide accessors in older Perl code. See\nperlootut for recommendations on OO coding in Perl.\n\nIf your class does have an \"AUTOLOAD\" method, we strongly recommend that you override \"can\"\nin your class as well. Your overridden \"can\" method should return a subroutine reference for\nany method that your \"AUTOLOAD\" responds to.\n"
                },
                {
                    "name": "Destructors",
                    "content": "When the last reference to an object goes away, the object is destroyed. If you only have one\nreference to an object stored in a lexical scalar, the object is destroyed when that scalar\ngoes out of scope. If you store the object in a package global, that object may not go out of\nscope until the program exits.\n\nIf you want to do something when the object is destroyed, you can define a \"DESTROY\" method\nin your class. This method will always be called by Perl at the appropriate time, unless the\nmethod is empty.\n\nThis is called just like any other method, with the object as the first argument. It does not\nreceive any additional arguments. However, the $[0] variable will be read-only in the\ndestructor, so you cannot assign a value to it.\n\nIf your \"DESTROY\" method throws an exception, this will not cause any control transfer beyond\nexiting the method.  The exception will be reported to \"STDERR\" as a warning, marked \"(in\ncleanup)\", and Perl will continue with whatever it was doing before.\n\nBecause \"DESTROY\" methods can be called at any time, you should localize any global status\nvariables that might be set by anything you do in your \"DESTROY\" method.  If you are in doubt\nabout a particular status variable, it doesn't hurt to localize it.  There are five global\nstatus variables, and the safest way is to localize all five of them:\n\nsub DESTROY {\nlocal($., $@, $!, $^E, $?);\nmy $self = shift;\n...;\n}\n\nIf you define an \"AUTOLOAD\" in your class, then Perl will call your \"AUTOLOAD\" to handle the\n\"DESTROY\" method. You can prevent this by defining an empty \"DESTROY\", like we did in the\nautoloading example.  You can also check the value of $AUTOLOAD and return without doing\nanything when called to handle \"DESTROY\".\n\nGlobal Destruction\n\nThe order in which objects are destroyed during the global destruction before the program\nexits is unpredictable. This means that any objects contained by your object may already have\nbeen destroyed. You should check that a contained object is defined before calling a method\non it:\n\nsub DESTROY {\nmy $self = shift;\n\n$self->{handle}->close() if $self->{handle};\n}\n\nYou can use the \"${^GLOBALPHASE}\" variable to detect if you are currently in the global\ndestruction phase:\n\nsub DESTROY {\nmy $self = shift;\n\nreturn if ${^GLOBALPHASE} eq 'DESTRUCT';\n\n$self->{handle}->close();\n}\n\nNote that this variable was added in Perl 5.14.0. If you want to detect the global\ndestruction phase on older versions of Perl, you can use the \"Devel::GlobalDestruction\"\nmodule on CPAN.\n\nIf your \"DESTROY\" method issues a warning during global destruction, the Perl interpreter\nwill append the string \" during global destruction\" to the warning.\n\nDuring global destruction, Perl will always garbage collect objects before unblessed\nreferences. See \"PERLDESTRUCTLEVEL\" in perlhacktips for more information about global\ndestruction.\n"
                },
                {
                    "name": "Non-Hash Objects",
                    "content": "All the examples so far have shown objects based on a blessed hash.  However, it's possible\nto bless any type of data structure or referent, including scalars, globs, and subroutines.\nYou may see this sort of thing when looking at code in the wild.\n\nHere's an example of a module as a blessed scalar:\n\npackage Time;\n\nuse strict;\nuse warnings;\n\nsub new {\nmy $class = shift;\n\nmy $time = time;\nreturn bless \\$time, $class;\n}\n\nsub epoch {\nmy $self = shift;\nreturn $$self;\n}\n\nmy $time = Time->new();\nprint $time->epoch();\n"
                },
                {
                    "name": "Inside-Out objects",
                    "content": "In the past, the Perl community experimented with a technique called \"inside-out objects\". An\ninside-out object stores its data outside of the object's reference, indexed on a unique\nproperty of the object, such as its memory address, rather than in the object itself. This\nhas the advantage of enforcing the encapsulation of object attributes, since their data is\nnot stored in the object itself.\n\nThis technique was popular for a while (and was recommended in Damian Conway's Perl Best\nPractices), but never achieved universal adoption. The Object::InsideOut module on CPAN\nprovides a comprehensive implementation of this technique, and you may see it or other\ninside-out modules in the wild.\n\nHere is a simple example of the technique, using the Hash::Util::FieldHash core module. This\nmodule was added to the core to support inside-out object implementations.\n\npackage Time;\n\nuse strict;\nuse warnings;\n\nuse Hash::Util::FieldHash 'fieldhash';\n\nfieldhash my %timefor;\n\nsub new {\nmy $class = shift;\n\nmy $self = bless \\( my $object ), $class;\n\n$timefor{$self} = time;\n\nreturn $self;\n}\n\nsub epoch {\nmy $self = shift;\n\nreturn $timefor{$self};\n}\n\nmy $time = Time->new;\nprint $time->epoch;\n"
                },
                {
                    "name": "Pseudo-hashes",
                    "content": "The pseudo-hash feature was an experimental feature introduced in earlier versions of Perl\nand removed in 5.10.0. A pseudo-hash is an array reference which can be accessed using named\nkeys like a hash. You may run in to some code in the wild which uses it. See the fields\npragma for more information.\n"
                }
            ]
        },
        "SEE ALSO": {
            "content": "A kinder, gentler tutorial on object-oriented programming in Perl can be found in perlootut.\nYou should also check out perlmodlib for some style guides on constructing both modules and\nclasses.\n\n\n\nperl v5.34.0                                 2025-07-25                                   PERLOBJ(1)",
            "subsections": []
        }
    },
    "summary": "perlobj - Perl object reference",
    "flags": [],
    "examples": [],
    "see_also": []
}