{
    "content": [
        {
            "type": "text",
            "text": "# perlobj (perldoc)\n\n## NAME\n\nperlobj - Perl object reference\n\n## DESCRIPTION\n\nThis document provides a reference for Perl's object orientation features. If you're looking for\nan introduction to object-oriented programming in Perl, please see perlootut.\n\n## Sections\n\n- **NAME**\n- **DESCRIPTION** (15 subsections)\n- **SEE ALSO**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "perlobj",
        "section": "",
        "mode": "perldoc",
        "summary": "perlobj - Perl object reference",
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 25,
                "subsections": [
                    {
                        "name": "An Object is Simply a Data Structure",
                        "lines": 143
                    },
                    {
                        "name": "Method Invocation",
                        "lines": 28
                    },
                    {
                        "name": "Inheritance",
                        "lines": 170
                    },
                    {
                        "name": "Writing Constructors",
                        "lines": 40
                    },
                    {
                        "name": "Attributes",
                        "lines": 44
                    },
                    {
                        "name": "An Aside About Smarter and Safer Code",
                        "lines": 7
                    },
                    {
                        "name": "Method Call Variations",
                        "lines": 86
                    },
                    {
                        "name": "Invoking Class Methods",
                        "lines": 96
                    },
                    {
                        "name": "The UNIVERSAL Class",
                        "lines": 5
                    },
                    {
                        "name": "isa",
                        "lines": 13
                    },
                    {
                        "name": "can",
                        "lines": 70
                    },
                    {
                        "name": "Destructors",
                        "lines": 64
                    },
                    {
                        "name": "Non-Hash Objects",
                        "lines": 26
                    },
                    {
                        "name": "Inside-Out objects",
                        "lines": 42
                    },
                    {
                        "name": "Pseudo-hashes",
                        "lines": 5
                    }
                ]
            },
            {
                "name": "SEE ALSO",
                "lines": 3,
                "subsections": []
            }
        ],
        "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 for\nan 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 implements\nobjects from scratch then this document will help you understand exactly how Perl does object\norientation.\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 special\nsyntax for constructing an object. Objects are merely Perl data structures (hashes, arrays,\nscalars, filehandles, etc.) that have been explicitly associated with a particular class.\n\nThat explicit association is created by the built-in \"bless\" function, which is typically used\nwithin 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, but\nthere is no requirement to do so. Any subroutine that blesses a data structure into a class is a\nvalid 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. In\nthe 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 as\nour 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 with\nthe object. Typically, code inside the class can treat the hash as an accessible data structure,\nwhile code outside the class should always treat the object as opaque. This is called\nencapsulation. Encapsulation means that the user of an object does not have to know how it is\nimplemented. 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\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 that\nthe variable refers to. We are not blessing the reference itself, nor the variable that contains\nthat reference. That's why the second call to \"blessed( $bar )\" returns false. At that point\n$bar is no longer storing a reference to an object.\n\nYou will sometimes see older books or documentation mention \"blessing a reference\" or describe\nan object as a \"blessed reference\", but this is incorrect. It isn't the reference that is\nblessed as an object; it's the thing the reference refers to (i.e. the referent).\n\nA Class is Simply a Package\nPerl does not provide any special syntax for class definitions. A package is simply a namespace\ncontaining variables and subroutines. The only difference is that in a class, the subroutines\nmay expect a reference to an object or the name of a class as the first argument. This is purely\na matter of convention, so a class may contain both methods and subroutines which *don't*\noperate 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, which\nwe 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 discouraged\nexcept 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 by\nthe Perl core, and provides several default methods, such as \"isa()\", \"can()\", and \"VERSION()\".\nThe \"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 up\nthe class to implement. See the \"Writing Accessors\" section for details.\n\nA Method is Simply a Subroutine\nPerl 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 name),\nand 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 argument\nto the method. That means when we call \"Critter->new()\", the \"new()\" method receives the string\n\"Critter\" as its first argument. When we call \"$fred->speak()\", the $fred variable is passed as\nthe first argument to \"speak()\".\n\nJust as with any Perl subroutine, all of the arguments passed in @ are aliases to the original\nargument. This includes the object itself. If you assign directly to $[0] you will change the\ncontents of the variable that holds the reference to the object. We recommend that you don't do\nthis 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 left\nhand side is a package name, it looks for the method in that package. If the left hand side is\nan object, then Perl looks for the method in the package that the object has been blessed into.\n\nIf the left hand side is neither a package name nor an object, then the method call will cause\nan 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 available\nto the child class. If you attempt to call a method on an object that isn't defined in its own\nclass, 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 \"save()\"\nmethod 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 parent\nclass'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\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 methods.\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\" class,\nthe \"speak()\" method in the \"B\" class can still call \"SUPER::speak()\" and expect it to correctly\nlook in the parent class of \"B\" (i.e the class the method call is in), not in the parent class\nof \"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\nMultiple inheritance often indicates a design problem, but Perl always gives you enough rope to\nhang 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\nMethod resolution order only matters in the case of multiple inheritance. In the case of single\ninheritance, 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 with\nthe first parent in the @ISA array, and then searches all of its parents, grandparents, etc. If\nit fails to find the method, it then goes to the next parent in the original class's @ISA array\nand 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 the\nmro documentation for more details on this feature.\n\nMethod Resolution Caching\nWhen Perl searches for a method, it caches the lookup so that future calls to the method do not\nneed to search for it again. Changing a class's parent class or adding subroutines to a class\nwill 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 class\nmust implement its own constructor. A constructor is simply a class method that returns a\nreference to a new object.\n\nThe constructor can also accept additional parameters that define the object. Let's write a real\nconstructor 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 data.\n\nFor our \"File::MP3\" class, we can check to make sure that the path we're given ends with \".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-oriented\nlanguages, Perl provides no special syntax or support for declaring and manipulating attributes.\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 considered a\nbest 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 object\nlater while still preserving the original API.\n\nAn accessor lets you add additional code around attribute access. For example, you could apply a\ndefault to an attribute that wasn't set in the constructor, or you could validate that a new\nvalue for the attribute is acceptable.\n\nFinally, using accessors makes inheritance much simpler. Subclasses can use the accessors rather\nthan having to know how a parent class is implemented internally.\n\nWriting Accessors\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-only\nand 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, nor\ndo 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 is\nalso incredibly tedious. There are a lot of modules on CPAN that can help you write safer and\nmore 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\nPerl allows you to call methods using their fully qualified name (the package and method name):\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 for\nthe \"save\" method starts in the \"File\" class, skipping any \"save\" method the \"File::MP3\" class\nmay 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 ancestor\nclass, 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 a\nfully-qualified name. See the earlier \"Inheritance\" section for details.\n\nMethod Names as Strings\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\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\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\nPerl also lets you use a dereferenced scalar reference in a method call. That's a mouthful, so\nlet'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\nUnder the hood, Perl filehandles are instances of the \"IO::Handle\" or \"IO::File\" class. Once you\nhave an open filehandle, you can call methods on it. Additionally, you can call methods on the\n\"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\nOutside of the file handle case, use of this syntax is discouraged as it can confuse the Perl\ninterpreter. See below for more details.\n\nPerl supports another method invocation syntax called \"indirect object\" notation. This syntax is\ncalled \"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 method\nprovided by the \"File\" class or simply a subroutine that expects a file object as its first\nargument.\n\nWhen used with class methods, the problem is even worse. Because Perl allows subroutine names to\nbe written as barewords, Perl has to guess whether the bareword after the method is a class name\nor subroutine name. In other words, Perl can resolve the syntax as either \"File->new( $path,\n$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 it\nin 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\n\"bless\", \"blessed\", and \"ref\"\nAs we saw earlier, an object is simply a data structure that has been blessed into a class via\nthe \"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 second\nform, 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 \"blessed\"\nfunction 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 has\nbeen blessed into. If $thing doesn't contain a reference to a blessed object, the \"blessed\"\nfunction returns \"undef\".\n\nNote that \"blessed($thing)\" will also return false if $thing has been blessed into a class named\n\"0\". This is a possible, but quite pathological. Don't create a class named \"0\" unless you know\nwhat you're doing.\n\nSimilarly, Perl's built-in \"ref\" function treats a reference to a blessed object specially. If\nyou call \"ref($thing)\" and $thing holds a reference to an object, it will return the name of the\nclass that the object has been blessed into.\n\nIf you simply want to check that a variable contains an object reference, we recommend that you\nuse \"defined blessed($object)\", since \"ref\" returns true values for all references, not just\nobjects.\n"
                    },
                    {
                        "name": "The UNIVERSAL Class",
                        "content": "All classes automatically inherit from the UNIVERSAL class, which is built-in to the Perl core.\nThis class provides a number of methods, all of which can be called on either a class or an\nobject. You can also choose to override some of these methods in your class. If you do so, we\nrecommend that you follow the built-in semantics described below.\n"
                    },
                    {
                        "name": "isa",
                        "content": "The \"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 default,\nthis is equivalent to \"isa\". This method is provided for use by object system extensions\nthat implement roles, like \"Moose\" and \"Role::Tiny\".\n\nYou can also override \"DOES\" directly in your own classes. If you override this method, it\nshould never throw an exception.\n"
                    },
                    {
                        "name": "can",
                        "content": "The \"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 this\nis 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 overridden\nthe \"VERSION\" method.\n\nWe also recommend using this method to check whether a module has a sufficient version. The\ninternal implementation uses the version module to make sure that different types of version\nnumbers are compared correctly.\n\nAUTOLOAD\nIf you call a method that doesn't exist in a class, Perl will throw an error. However, if that\nclass or any of its parent classes defines an \"AUTOLOAD\" method, that \"AUTOLOAD\" method is\ncalled instead.\n\n\"AUTOLOAD\" is called as a regular method, and the caller will not know the difference. Whatever\nvalue 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 for\nyour class. Since this is a global, if you want to refer to do it without a package name prefix\nunder \"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 by\nfar. However, you may see this as a way to provide accessors in older Perl code. See perlootut\nfor recommendations on OO coding in Perl.\n\nIf your class does have an \"AUTOLOAD\" method, we strongly recommend that you override \"can\" in\nyour class as well. Your overridden \"can\" method should return a subroutine reference for any\nmethod 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 goes\nout of scope. If you store the object in a package global, that object may not go out of scope\nuntil the program exits.\n\nIf you want to do something when the object is destroyed, you can define a \"DESTROY\" method in\nyour class. This method will always be called by Perl at the appropriate time, unless the method\nis 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 status\nvariables, 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 anything\nwhen called to handle \"DESTROY\".\n\nGlobal Destruction\nThe order in which objects are destroyed during the global destruction before the program exits\nis unpredictable. This means that any objects contained by your object may already have been\ndestroyed. You should check that a contained object is defined before calling a method on 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 destruction\nphase on older versions of Perl, you can use the \"Devel::GlobalDestruction\" module on CPAN.\n\nIf your \"DESTROY\" method issues a warning during global destruction, the Perl interpreter will\nappend the string \" during global destruction\" to the warning.\n\nDuring global destruction, Perl will always garbage collect objects before unblessed references.\nSee \"PERLDESTRUCTLEVEL\" in perlhacktips for more information about global destruction.\n"
                    },
                    {
                        "name": "Non-Hash Objects",
                        "content": "All the examples so far have shown objects based on a blessed hash. However, it's possible to\nbless any type of data structure or referent, including scalars, globs, and subroutines. You may\nsee 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 has\nthe advantage of enforcing the encapsulation of object attributes, since their data is not\nstored 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 and\nremoved in 5.10.0. A pseudo-hash is an array reference which can be accessed using named keys\nlike a hash. You may run in to some code in the wild which uses it. See the fields pragma for\nmore information.\n"
                    }
                ]
            },
            "SEE ALSO": {
                "content": "A kinder, gentler tutorial on object-oriented programming in Perl can be found in perlootut. You\nshould also check out perlmodlib for some style guides on constructing both modules and classes.\n",
                "subsections": []
            }
        }
    }
}