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

📄 ch14.htm

📁 this is a book on pearl , simple example with explanation is given here. it could be beneficial for
💻 HTM
📖 第 1 页 / 共 5 页
字号:
<I>Start a new class called </I><TT><I>Inventory_item</I></TT><I>.The </I><TT><I>package</I></TT><I>keyword is used to introduce new classes and namespaces.<BR>Define the </I><TT><I>new()</I></TT><I>fuNCtion. This fuNCtion is responsible for constructing a newobject.<BR>The first parameter to the </I><TT><I>new()</I></TT><I>fuNCtion is the class name (</I><TT><I>Inventory_item</I></TT><I>).This is explained further in the sections &quot;Example: InitializingObject Properties&quot; and &quot;Static Versus Regular Methods&quot;later in the chapter.<BR>The </I><TT><I>bless()</I></TT><I>fuNCtion is used to change the data type of the anonymous hashto </I><TT><I>$class</I></TT><I> or</I><TT><I>Inventory_item</I></TT><I>.Because this is the last statement in the method, its value willbe returned as the value of the fuNCtion. I feel that using thereturn statement to explicitly return a value would clutter thecode in this situation.<BR>An anonymous hash is used to hold the properties for the class.For the moment, their values are undefined. Assigning values toproperties is discussed in the section &quot;Example: InitializingProperties&quot; later in this chapter.<BR>Switch to the package called </I><TT><I>main</I></TT><I>.This is the default place for variables and code to go (technically,this is called a namespace). If no classes are defined in yourscript, then this line is not needed.<BR>Assign an instaNCe of the </I><TT><I>Inventory_item</I></TT><I>class to the </I><TT><I>$item variable</I></TT><I>.</I></BLOCKQUOTE><HR><BLOCKQUOTE><B>Listing 14.1&nbsp;&nbsp;14LST01.PL-Defining the </B><TT><B><FONT FACE="Courier">Inventory_item</FONT></B></TT><B>Class<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>package Inventory_item;    sub new {        my($class) = shift;            bless {            &quot;PART_NUM&quot;    =&gt; undef,            &quot;QTY_ON_HAND&quot; =&gt; undef        }, $class;    }package main;   $item = Inventory_item-&gt;new();</PRE></BLOCKQUOTE><HR><P>There is a <I>lot</I> of new stuff in this small ten-line listing,and you'll need to review it carefully to glean the informationneeded to understand everything that is happening. You'll alsostart to translate between the Perl keywords and the object-orientedterminology.<P>The first line, <TT>package Inventory_item</TT>;says two things, depending on if you are thinking in terms ofobjects or in terms of Perl. When considering objects, it beginsthe definition of a class. When considering Perl, it means thata specific namespace will be used.<P>You read a little bit about namespace in <A HREF="ch3.htm" >Chapter 3</A> &quot;Variables.&quot;A <I>namespace</I> is used to keep one set of names from interferingwith another. For example, you can have a variable named bar anda fuNCtion called <TT>bar</TT>, andthe names will not conflict because variables and fuNCtions eachhave their own namespace.<P>The <TT>package</TT> keyword letsyou create your own namespace. This lets you create more thanone fuNCtion called <TT>new()</TT>as long as each is in its own package or namespace. If you needto refer to a specific fuNCtion in a specific namespace, you canuse <TT>Inventory_item&#173;&gt;new</TT>,<TT>Inventory_item::new</TT>, or <TT>Inventory_item'new</TT>.Which notation you use will probably depend on your background.Object-oriented folks will probably want to use the -&gt; notation.<P>The second line, <TT>sub new</TT>,starts the definition of a fuNCtion. It has become accepted practicein the object-oriented world to construct new objects with the<TT>new()</TT> method. This is calledthe class <I>constructor</I>. This might be a good time to emphasizethat the class definition is a template. It's only when the <TT>new()</TT>fuNCtion is called that an object is created or <I>instantiated</I>.Instantiation means that memory is allocated from your computer'smemory pool and devoted to the use of this specific object. The<TT>new()</TT> fuNCtion normally returnsa refereNCe to an anonymous hash. Therefore, the <TT>new()</TT>fuNCtion should never be called unless you are assigning its returnvalue to a variable. If you don't store the refereNCe into a scalarvariable for later use, you'll never be able to access the anonymoushash inside the object. For all intents and purposes, the anonymoushash <I>is</I> the object.<BR><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD><B>Note</B></TD></TR><TR><TD><BLOCKQUOTE>Not all objects are represented by hashes. If you need an object to emulate a gas tank, perhaps an anonymous scalar would be sufficient to hold the number of gallons of gas left in the tank. However, you'll see that working with hashes is quite easy oNCe you learn how. Hashes give you tremendous flexibility to solve programming problems.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>There is nothing magic about the new fuNCtion name. You couldcall the fuNCtion that creates new objects <TT>create()</TT>or <TT>build()</TT> or anything else,but don't. The standard is <TT>new()</TT>,and everyone who reads your program or uses your classes willlook for a <TT>new()</TT> fuNCtion.If they don't find one, confusion might set in. There are so fewstandards in the programming business. When they exist, it's usuallya good idea to follow them.<P>The <TT>bless()</TT> fuNCtion on thethird line changes the data type of its first parameter to thestring value of its second parameter. In the situation shown here,the data type is changed to the name of the package, <TT>Inventory_item</TT>.Using <TT>bless()</TT> to change thedata type of a refereNCe causes the <TT>ref()</TT>fuNCtion to return the new data type. This potentially confusingpoint is explained further in the section &quot;Example: Blessthe Hash and Pass the RefereNCe&quot; later in this chapter.<BR><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD><B>Note</B></TD></TR><TR><TD><BLOCKQUOTE>I used the <TT>bless()</TT> fuNCtion without using parentheses to surround the parameters. While Perl lets you do this, I have been studiously using parentheses to avoid certain issues of precedeNCe that seem beyond the scope of this book. In this special instaNCe, where the anonymous hash is one of the parameters, I feel that using parentheses clutters the source code.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>Embedded inside the <TT>bless()</TT>fuNCtion call is the creation of an anonymous hash that holdsthe properties of the class. The hash definition is repeated herefor your convenieNCe:<BLOCKQUOTE><PRE>{    &quot;PART_NUM&quot;    =&gt; undef,    &quot;QTY_ON_HAND&quot; =&gt; undef};</PRE></BLOCKQUOTE><P>Nothing significant is happening here that you haven't seen before.Each entry in the hash is a different property of the class. Forthe moment, I have assigned the undefined value to the value partof the entries. Soon you'll see how to properly initialize them.<P>After the <TT>new()</TT> fuNCtionis defined, there is another package statement:<BLOCKQUOTE><PRE>package main;</PRE></BLOCKQUOTE><P>There is no object-oriented way to interpret this statement. Itsimply tells Perl to switch back to using the <TT>main</TT>namespace. Don't be fooled into thinking that there is a <TT>main</TT>class somewhere. There isn't.<BR><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD><B>Caution</B></TD></TR><TR><TD><BLOCKQUOTE>While you could create a <TT>main</TT> class by defining the <TT>new()</TT> fuNCtion after the <TT>package main;</TT> statement, things might get to be confusing, so don't do it!</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>The last statement in the file is really the first line that getsexecuted. Everything else in the script has been class and methoddefinitions.<BLOCKQUOTE><PRE>   $item = Inventory_item-&gt;new();</PRE></BLOCKQUOTE><P>By now, you've probably guessed what this statement does. It assignsa refereNCe to the anonymous hash to <TT>$item</TT>.You can derefereNCe <TT>$item</TT>in order to determine the value of the entries in the hash. Ifyou use the <TT>ref()</TT> fuNCtionto determine the data type of <TT>$item</TT>,you find that its value is <TT>Inventory_item</TT>.<P>Here are some key items to remember about objects in Perl:<BLOCKQUOTE><B>All objects are anonymous hashes:</B> While not strictly true,perhaps it should be. Also, most of the examples in this bookfollow this rule. This means that most of the <TT>new()</TT>methods you see return a refereNCe to a hash.</BLOCKQUOTE><BLOCKQUOTE><TT><B><FONT FACE="Courier">bless()</FONT></B></TT><B> changesthe data type of the anonymous hash:</B> The data type is changedto the name of the class.</BLOCKQUOTE><BLOCKQUOTE><B>The anonymous hash itself is blessed:</B> This means that refereNCesto the hash are not blessed. This coNCept is probably a littleuNClear. I had trouble figuring it out myself. The next sectionclarifies this point and uses an example.</BLOCKQUOTE><BLOCKQUOTE><B>Objects can belong to only one class at a time:</B> You canuse the <TT>bless()</TT> fuNCtionto change the ownership at any time. However, don't do this unlessyou have a good reason.</BLOCKQUOTE><BLOCKQUOTE><B>The </B><TT><B><FONT FACE="Courier">-&gt;</FONT></B></TT><B>operator is used to call a method associated with a class:</B>There are two different ways to invoke or call class methods:</BLOCKQUOTE><BLOCKQUOTE><PRE>$item = new Inventory_item;</PRE></BLOCKQUOTE><P>or<BLOCKQUOTE><PRE>$item = Inventory_item-&gt;new();</PRE></BLOCKQUOTE><P>Both of these techniques are equivalent, but the <TT>-&gt;</TT>style is preferred by object-oriented folks.<H3><A NAME="ExampleBlesstheHashandPasstheRefereNCe">Example: Bless the Hash and Pass the RefereNCe</A></H3><P>If you recall from <A HREF="ch8.htm" >Chapter 8</A> the <TT>ref()</TT>fuNCtion returns either the undefined value or a string indicatingthe parameter's data type (<TT>SCALAR</TT>,<TT>ARRAY</TT>, <TT>HASH</TT>,<TT>CODE</TT>, or <TT>REF</TT>).When classes are used, these data types don't provide enough information.<P>This is why the <TT>bless()</TT> fuNCtionwas added to the language. It lets you change the data type ofany variable. You can change the data type to any string valueyou like. Most often, the data type is changed to reflect theclass name.<P>It is important to understand that the variable itself will haveits data type changed. The following lines of code should makethis clear:<BLOCKQUOTE><PRE>$foo    = { };$fooRef = $foo;print(&quot;data of \$foo is &quot;    . ref($foo)    . &quot;\n&quot;);print(&quot;data of \$fooRef is &quot; . ref($fooRef) . &quot;\n&quot;);bless($foo, &quot;Bar&quot;);print(&quot;data of \$foo is &quot;    . ref($foo)    . &quot;\n&quot;);print(&quot;data of \$fooRef is &quot; . ref($fooRef) . &quot;\n&quot;);</PRE></BLOCKQUOTE><P>This program displays the following:<BLOCKQUOTE><PRE>data of $foo is HASHdata of $fooRef is HASHdata of $foo is Bardata of $fooRef is Bar</PRE></BLOCKQUOTE><P>After the data type is changed, the <TT>ref($fooRef)</TT>fuNCtion call returns <TT>Bar</TT>instead of the old value of <TT>HASH</TT>.This can happen only if the variable itself has been altered.This example also shows that the <TT>bless()</TT>fuNCtion works outside the object-oriented world.<H3><A NAME="ExampleInitializingProperties">Example: Initializing Properties</A></H3><P>You now know how to instantiate a new class by using a <TT>new()</TT>fuNCtion and how to create class properties (the class information)with undefined values. Let's look at how to give those propertiessome real values. You need to start by looking at the <TT>new()</TT>fuNCtion from Listing 14.1. It's repeated here so you don't needto flip back to look for it.<BLOCKQUOTE><PRE>sub new {        my($class) = shift;        bless {            &quot;PART_NUM&quot;    =&gt; undef,            &quot;QTY_ON_HAND&quot; =&gt; undef        }, $class;}</PRE></BLOCKQUOTE><P>The <TT>new()</TT> fuNCtion is a <I>static</I>method. Static methods are not associated with any specificobject. This makes sense because the <TT>new()</TT>fuNCtion is designed to create objects. It can't be associatedwith an object that doesn't exist yet, can it?<P>The first argument to a static method is always the class name.Perl takes the name of the class from in front of the -&gt; operatorand adds it to the beginning of the parameter array, which ispassed to the <TT>new()</TT> fuNCtion.<P>If you want to pass two values into the <TT>new()</TT>fuNCtion to initialize the class properties, you can modify themethod to look for additional arguments as in the following:<BLOCKQUOTE><PRE>sub new {

⌨️ 快捷键说明

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