⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch13_01.htm

📁 By Tom Christiansen and Nathan Torkington ISBN 1-56592-243-3 First Edition, published August 1998
💻 HTM
📖 第 1 页 / 共 3 页
字号:
<HTML><HEAD><METANAME="DC.title"CONTENT="Perl Cookbook"><METANAME="DC.creator"CONTENT="Tom Christiansen &amp; Nathan Torkington"><METANAME="DC.publisher"CONTENT="O'Reilly &amp; Associates, Inc."><METANAME="DC.date"CONTENT="1999-07-02T01:42:10Z"><METANAME="DC.type"CONTENT="Text.Monograph"><METANAME="DC.format"CONTENT="text/html"SCHEME="MIME"><METANAME="DC.source"CONTENT="1-56592-243-3"SCHEME="ISBN"><METANAME="DC.language"CONTENT="en-US"><METANAME="generator"CONTENT="Jade 1.1/O'Reilly DocBook 3.0 to HTML 4.0"><LINKREV="made"HREF="mailto:online-books@oreilly.com"TITLE="Online Books Comments"><LINKREL="up"HREF="index.htm"TITLE="Perl Cookbook"><LINKREL="prev"HREF="ch12_20.htm"TITLE="12.19. Program: Finding Versions and Descriptions of Installed Modules"><LINKREL="next"HREF="ch13_02.htm"TITLE="13.1. Constructing an Object"></HEAD><BODYBGCOLOR="#FFFFFF"><img alt="Book Home" border="0" src="gifs/smbanner.gif" usemap="#banner-map" /><map name="banner-map"><area shape="rect" coords="1,-2,616,66" href="index.htm" alt="Perl Cookbook"><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><p><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch12_20.htm"TITLE="12.19. Program: Finding Versions and Descriptions of Installed Modules"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 12.19. Program: Finding Versions and Descriptions of Installed Modules"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1"></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch13_02.htm"TITLE="13.1. Constructing an Object"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 13.1. Constructing an Object"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="chapter"><H1CLASS="chapter"><ACLASS="title"NAME="ch13-15948">13. Classes, Objects, and Ties</A></H1><DIVCLASS="htmltoc"><P><B>Contents:</B><BR><ACLASS="sect1"HREF="#ch13-31898"TITLE="13.0. Introduction">Introduction</A><BR><ACLASS="sect1"HREF="ch13_02.htm"TITLE="13.1. Constructing an Object">Constructing an Object</A><BR><ACLASS="sect1"HREF="ch13_03.htm"TITLE="13.2. Destroying an Object">Destroying an Object</A><BR><ACLASS="sect1"HREF="ch13_04.htm"TITLE="13.3. Managing Instance Data">Managing Instance Data</A><BR><ACLASS="sect1"HREF="ch13_05.htm"TITLE="13.4. Managing Class Data">Managing Class Data</A><BR><ACLASS="sect1"HREF="ch13_06.htm"TITLE="13.5. Using Classes as Structs">Using Classes as Structs</A><BR><ACLASS="sect1"HREF="ch13_07.htm"TITLE="13.6. Cloning Objects">Cloning Objects</A><BR><ACLASS="sect1"HREF="ch13_08.htm"TITLE="13.7. Calling Methods Indirectly">Calling Methods Indirectly</A><BR><ACLASS="sect1"HREF="ch13_09.htm"TITLE="13.8. Determining Subclass Membership">Determining Subclass Membership</A><BR><ACLASS="sect1"HREF="ch13_10.htm"TITLE="13.9. Writing an Inheritable Class">Writing an Inheritable Class</A><BR><ACLASS="sect1"HREF="ch13_11.htm"TITLE="13.10. Accessing Overridden Methods">Accessing Overridden Methods</A><BR><ACLASS="sect1"HREF="ch13_12.htm"TITLE="13.11. Generating Attribute Methods Using AUTOLOAD">Generating Attribute Methods Using AUTOLOAD</A><BR><ACLASS="sect1"HREF="ch13_13.htm"TITLE="13.12. Solving the Data Inheritance Problem">Solving the Data Inheritance Problem</A><BR><ACLASS="sect1"HREF="ch13_14.htm"TITLE="13.13. Coping with Circular Data Structures">Coping with Circular Data Structures</A><BR><ACLASS="sect1"HREF="ch13_15.htm"TITLE="13.14. Overloading Operators">Overloading Operators</A><BR><ACLASS="sect1"HREF="ch13_16.htm"TITLE="13.15. Creating Magic Variables with tie">Creating Magic Variables with tie</A></P><P></P></DIV><DIVCLASS="epigraph"ALIGN="right"><PCLASS="para"ALIGN="right"><I>All the world over, I will back the masses against the classes.</I></P><PCLASS="attribution"ALIGN="right">-&nbsp;William E. Gladstone <CITECLASS="citetitle">Speech at Liverpool, 28 June 1886 </CITE></P></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch13-31898">13.0. Introduction</A></H2><PCLASS="para">Along with references and modules, release 5.000 of Perl added objects. As usual, Perl doesn't try to enforce one true style but embraces many. This helps more people do their job the way they want to do it.</P><PCLASS="para">You don't have to use objects to write programs, unlike Java, where programs are instances of objects. If you want to, though, you can write Perl programs that use nearly every weapon in the object-oriented arsenal. Perl supports classes and objects, single and multiple inheritance, instance methods and class methods, access to overridden methods, constructors and destructors, operator overloading, proxy methods through autoloading, delegation, a rooted hierarchy for all objects, and two levels of garbage collection.</P><PCLASS="para">You can use as many or as few object-oriented techniques as you want and need. Ties are the only parts of Perl where you must use object orientation. And even then, only the module implementor need be aware of this; the casual user gets to remain blissfully unaware of the internal mechanics. Ties, discussed in <ACLASS="xref"HREF="ch13_16.htm"TITLE="Creating Magic Variables with tie">Recipe 13.15</A>, let you transparently intercept access to a variable. For example, you can use ties to make a hash that allows lookups by key or value.</P><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch13-chap13_under_0">Under the Hood</A></H3><PCLASS="para"><ACLASS="indexterm"NAME="ch13-idx-1000004418-0"></A>If you ask ten people what object orientation is, you'll get ten different answers. People bandy about terms like abstraction and encapsulation, trying to isolate the basic units of object-oriented programming languages and give them big names to write papers and books about. Not all object-oriented languages offer the same features, yet they are still deemed object-oriented. This, of course, produces more papers and books.</P><PCLASS="para">We'll follow the nomenclature used in Perl's documentation, the <ICLASS="filename">perlobj </I>(1) manpage, and Chapter 5 of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A>, "Libraries, Modules, and Classes." An <EMCLASS="emphasis">object</EM><ACLASS="indexterm"NAME="ch13-idx-1000004419-0"></A><ACLASS="indexterm"NAME="ch13-idx-1000004419-1"></A><ACLASS="indexterm"NAME="ch13-idx-1000004419-2"></A> is a variable that belongs to a <EMCLASS="emphasis">class</EM>. <EMCLASS="emphasis">Methods</EM> are functions associated with a class or object. In Perl, a class is a package  &nbsp;-   and usually a module. An object is a reference to something that's been <EMCLASS="emphasis">blessed</EM><ACLASS="indexterm"NAME="ch13-idx-1000004420-0"></A><ACLASS="indexterm"NAME="ch13-idx-1000004420-1"></A> into a class. Blessing associates a referent with a class. This is done with the <CODECLASS="literal">bless</CODE> function, which takes one or two arguments. The first is a reference to the thing to bless, and the optional second argument is the package to bless it into.</P><PRECLASS="programlisting">$object = {};                       # hash referencebless($object, &quot;Data::Encoder&quot;);    # bless $object into Data::Encoder classbless($object);                     # bless $object into current package</PRE><PCLASS="para">The class name is the package name (<CODECLASS="literal">Data::Encoder</CODE> in the example above). Because classes are modules (usually), the code for the <CODECLASS="literal">Data::Encoder</CODE> class resides in the file <EMCLASS="emphasis">Data/Encoder.pm</EM>. As with traditional modules, the directory structure is purely for convenience; it implies nothing about inheritance, variable sharing, or anything else. Unlike a traditional module, though, an object module seldom if ever uses the Exporter. Access should be through method calls only, not imported functions or variables.</P><PCLASS="para">Once an object has been blessed, calling the <CODECLASS="literal">ref</CODE><ACLASS="indexterm"NAME="ch13-idx-1000004421-0"></A> function on its reference returns the name of its class instead of the fundamental type of referent:</P><PRECLASS="programlisting">$obj = [3,5];print ref($obj), &quot; &quot;, $obj-&gt;[1], &quot;\n&quot;;bless($obj, &quot;Human::Cannibal&quot;);print ref($obj), &quot; &quot;, $obj-&gt;[1], &quot;\n&quot;;<BCLASS="emphasis.bold">ARRAY 5</B><BCLASS="emphasis.bold">Human::Cannibal 5</B></PRE><PCLASS="para">As you can see, you can still dereference a reference once it has been blessed. Most frequently, objects are implemented as blessed hash references. You may use any kind of reference you want, but hash references are the most flexible. They let you have arbitrarily named data fields in an object.</P><PRECLASS="programlisting">$obj-&gt;{Stomach} = &quot;Empty&quot;;   # directly accessing an object's contents$obj-&gt;{NAME}    = &quot;Thag&quot;;        # uppercase field name to make it stand out (optional)</PRE><PCLASS="para">Although Perl permits it, it's considered poor form for any code outside the class to directly access the contents of an object. The point of objects, everyone agrees, is to give you a nominally opaque handle to <EMCLASS="emphasis">something</EM> that you access through designated methods only. This lets the maintainer of the class change its implementation without needing to change all application code that uses the class.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch13-chap13_methods_0">Methods</A></H3><PCLASS="para">To call a method, use <CODECLASS="literal">-&gt;</CODE><ACLASS="indexterm"NAME="ch13-idx-1000004426-0"></A>. Here, we call the <CODECLASS="literal">encode()</CODE> method of <CODECLASS="literal">$object</CODE> with the argument <CODECLASS="literal">&quot;data&quot;</CODE> and store the return value in <CODECLASS="literal">$encoded </CODE>:</P><PRECLASS="programlisting">$encoded = $object-&gt;encode(&quot;data&quot;);</PRE><PCLASS="para">This is an <EMCLASS="emphasis">object method</EM><ACLASS="indexterm"NAME="ch13-idx-1000004427-0"></A><ACLASS="indexterm"NAME="ch13-idx-1000004427-1"></A>, because we call the method on an object. We can also have <EMCLASS="emphasis">class methods</EM>, methods called on class names.</P><PRECLASS="programlisting">$encoded = Data::Encoder-&gt;encode(&quot;data&quot;);</PRE><PCLASS="para">Invoking a method calls the function in the corresponding class, implicitly passing as the initial argument either a reference for object methods or a string for class methods. <ACLASS="xref"HREF="ch13_08.htm"

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -