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

📄 ch31_09.htm

📁 编程珍珠,里面很多好用的代码,大家可以参考学习呵呵,
💻 HTM
字号:
<html><head><title>use fields (Programming Perl)</title><!-- STYLESHEET --><link rel="stylesheet" type="text/css" href="../style/style1.css"><!-- METADATA --><!--Dublin Core Metadata--><meta name="DC.Creator" content=""><meta name="DC.Date" content=""><meta name="DC.Format" content="text/xml" scheme="MIME"><meta name="DC.Generator" content="XSLT stylesheet, xt by James Clark"><meta name="DC.Identifier" content=""><meta name="DC.Language" content="en-US"><meta name="DC.Publisher" content="O'Reilly &amp; Associates, Inc."><meta name="DC.Source" content="" scheme="ISBN"><meta name="DC.Subject.Keyword" content=""><meta name="DC.Title" content="use fields"><meta name="DC.Type" content="Text.Monograph"></head><body><!-- START OF BODY --><!-- TOP BANNER --><img src="gifs/smbanner.gif" usemap="#banner-map" border="0" alt="Book Home"><map name="banner-map"><AREA SHAPE="RECT" COORDS="0,0,466,71" HREF="index.htm" ALT="Programming Perl"><AREA SHAPE="RECT" COORDS="467,0,514,18" HREF="jobjects/fsearch.htm" ALT="Search this book"></map><!-- TOP NAV BAR --><div class="navbar"><table width="515" border="0"><tr><td align="left" valign="top" width="172"><a href="ch31_08.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0"></a></td><td align="center" valign="top" width="171"><a href="ch31_01.htm">Chapter 31: Pragmatic Modules</a></td><td align="right" valign="top" width="172"><a href="ch31_10.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0"></a></td></tr></table></div><hr width="515" align="left"><!-- SECTION BODY --><h2 class="sect1">31.9. use fields</h2><p>In the <tt class="literal">Pet</tt> module:<blockquote><pre class="programlisting">package Pet;use strict;use fields qw(name weight _Pet_pid);my $PID = 0;sub new {    my Pet $self = shift;    unless (ref $self) {        $self = fields::new($self);        $self-&gt;{_Pet_pid} = "this is Pet's secret ID";    }    $self-&gt;{name} = "Hey, you!";    $self-&gt;{weight} = 20;    return $self;}1;</pre></blockquote>In a separate program, <em class="emphasis">demopet</em>:<blockquote><pre class="programlisting">use Pet;my Pet $rock = new Pet;           # typed lexical$rock-&gt;{name}     = "quartz";           $rock-&gt;{weight}   = "2kg";$rock-&gt;{_Pet_pid} = 1233;         # private attribute$rock-&gt;{color}    = "blue";       # generates compile-time error</pre></blockquote>In the <tt class="literal">Dog</tt> module:<blockquote><pre class="programlisting">package Dog;use strict;use base 'Pet';                   # inherit fields and methods from Petuse fields qw(name pedigree);     # override Pet name attribute,                                  # add new pedigree attributeuse fields qw(wag _Dog_private);  # not shared with Petsub new {    my $class = shift;    my $self = fields::new($class);    $self-&gt;SUPER::new();          # init base fields    $self-&gt;{pedigree} = "none";   # init own fields    return $self;}</pre></blockquote>In a separate program, <em class="emphasis">demodog</em>:<blockquote><pre class="programlisting">use Dog;my Dog $spot = new Dog;           # typed lexical$spot-&gt;{name}     = "Theloneus";  # not inherited$spot-&gt;{weight}   = "30lbs";      # inherited$spot-&gt;{pedigree} = "mutt";       # not inherited$spot-&gt;{color}    = "brown";      # generates compile-time error$spot-&gt;{_Pet_pid} = 3324;         # generates compile-time error</pre></blockquote></p><p>The <tt class="literal">fields</tt> pragma provides a method of declaringclass fields that can be type checked at compile time.  This relies ona feature known as pseudohashes: if a typed lexical variable(<tt class="literal">my Pet $rock</tt>) is holding a reference (the<tt class="literal">Pet</tt> object) and is used to access a hash element(<tt class="literal">$rock-&gt;{name}</tt>), and if there exists a packagewith the same name as the declared type that has set up class fieldsusing the <tt class="literal">fields</tt> pragma, then the operation isturned into an array access at compile time, provided the fieldspecified is valid.</p><p>The related <tt class="literal">base</tt> pragma will combine fields frombase classes and any fields declared using the<tt class="literal">fields</tt> pragma.  This enables field inheritance towork properly.</p><p>Field names that start with an underscore character are made private tothe class and are not visible to subclasses.  Inherited fields can beoverridden but will generate a warning if warnings are enabled.</p><p>The effect of all this is that you can have objects with named fieldswhich are as compact as arrays and as fast to access.  This only worksas long as the objects are accessed through properly typed lexical variables, though. If the variables are not typed, access is only checked at run time, so your program runs slower because it has to do both a hash access and an array access.  In addition to field declarations, the following functionsare supported:</p><dl><dt><b><tt class="literal">new</tt></b></dt><dd><p>The <tt class="literal">fields::new</tt> function creates and blesses apseudohash into the specified class (which may also be specified bypassing an object of that class).  The object is created with thefields declared earlier for that class using the<tt class="literal">fields</tt> pragma.  This makes it possible to write aconstructor like this:<blockquote><pre class="programlisting">package Critter::Sounds;use fields qw(cat dog bird);sub new {    my Critter::Sounds $self = shift;    $self = fields::new($self) unless ref $self;    $self-&gt;{cat} = 'meow';                          # scalar element    @$self{'dog','bird'} = ('bark','tweet');        # slice    return $self;}</pre></blockquote></p></dd><dt><b><tt class="literal">phash</tt></b></dt><dd><p>The <tt class="literal">fields::phash</tt> function creates and initializes a plain (unblessed)pseudohash.  You should always use this function to create pseudohashesinstead of creating them directly, in case we decide to change the implementation.</p></dd></dl><p>If the first argument to <tt class="literal">phash</tt> is a reference to an array, the pseudohash will be created with keys from that array.  If a second argument is supplied,it must also be a reference to an array whose elements will be used asthe values.  If the second array contains less elements than the first,the trailing elements of the pseudohash will not be initialized.This makes it particularly useful for creating a pseudohash fromsubroutine arguments:<blockquote><pre class="programlisting">sub dogtag {    my $tag = fields::phash([qw(name rank ser_num)], [@_]);}</pre></blockquote>Alternatively, you can pass a list key/value pairs that willbe used to construct the pseudohash:<blockquote><pre class="programlisting">my $tag = fields::phash(name =&gt; "Joe",                        rank =&gt; "captain",                        ser_num =&gt; 42);my $pseudohash = fields::phash(%args);</pre></blockquote>For more on pseudohashes, see the section "Pseudohashes" in <a href="ch08_01.htm">Chapter 8, "References"</a>.</p><p>The current implementation keeps the declared fields in the <tt class="literal">%FIELDS</tt>hash of the calling package, but this may change in future versions, soit's best to rely on this pragma's interface to manage your fields.</p><!-- BOTTOM NAV BAR --><hr width="515" align="left"><div class="navbar"><table width="515" border="0"><tr><td align="left" valign="top" width="172"><a href="ch31_08.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0"></a></td><td align="center" valign="top" width="171"><a href="index.htm"><img src="../gifs/txthome.gif" alt="Home" border="0"></a></td><td align="right" valign="top" width="172"><a href="ch31_10.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0"></a></td></tr><tr><td align="left" valign="top" width="172">31.8. use diagnostics</td><td align="center" valign="top" width="171"><a href="index/index.htm"><img src="../gifs/index.gif" alt="Book Index" border="0"></a></td><td align="right" valign="top" width="172">31.10. use filetest</td></tr></table></div><hr width="515" align="left"><!-- LIBRARY NAV BAR --><img src="../gifs/smnavbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links"><p><font size="-1"><a href="copyrght.htm">Copyright &copy; 2001</a> O'Reilly &amp; Associates. All rights reserved.</font></p><map name="library-map"> <area shape="rect" coords="2,-1,79,99" href="../index.htm"><area shape="rect" coords="84,1,157,108" href="../perlnut/index.htm"><area shape="rect" coords="162,2,248,125" href="../prog/index.htm"><area shape="rect" coords="253,2,326,130" href="../advprog/index.htm"><area shape="rect" coords="332,1,407,112" href="../cookbook/index.htm"><area shape="rect" coords="414,2,523,103" href="../sysadmin/index.htm"></map><!-- END OF BODY --></body></html>

⌨️ 快捷键说明

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