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

📄 ch01_02.htm

📁 编程珍珠,里面很多好用的代码,大家可以参考学习呵呵,
💻 HTM
📖 第 1 页 / 共 3 页
字号:
uninitialized variable automatically springs into existence as needed.Following the principle of least surprise, the variable is created with a nullvalue, either <tt class="literal">""</tt> or <tt class="literal">0</tt>.  Depending on where you use them, variableswill be interpreted automatically as strings, as numbers, or as "true"and "false" values (commonly called Boolean values).  Rememberhow important context is in human languages.  In Perl, various operatorsexpect certain kinds of singular values as parameters, so we will speakof those operators as "providing" or "supplying" a scalar context to thoseparameters. Sometimes we'll be more specific, and say it supplies anumeric context, a string context, or a Boolean context to thoseparameters.  (Later we'll also talk about list context, which is theopposite of scalar context.)  Perl will automatically convert the datainto the form required by the current context, within reason.  Forexample, suppose you said this:<blockquote><pre class="programlisting">$camels = '123';print $camels + 1, "\n";</pre></blockquote>The original value of <tt class="literal">$camels</tt> is a string, but it is converted to anumber to add <tt class="literal">1</tt> to it, and then converted back to a string to beprinted out as <tt class="literal">124</tt>.  The newline, represented by <tt class="literal">"\n"</tt>, is also instring context, but since it's already a string, no conversion isnecessary.  But notice that we had to use double quotes there--usingsingle quotes to say <tt class="literal">'\n'</tt> would result in a two-character stringconsisting of a backslash followed by an "<tt class="literal">n</tt>", which is not a newlineby anybody's definition.</p><p><a name="INDEX-71"></a><a name="INDEX-72"></a><a name="INDEX-73"></a><a name="INDEX-74"></a>So, in a sense, double quotes and single quotes are yet another way ofspecifying context.  The interpretation of the innards of a quotedstring depends on which quotes you use.  (Later, we'll see some otheroperators that work like quotes syntactically but use the string insome special way, such as for pattern matching or substitution.  Theseall work like double-quoted strings too.  The <em class="emphasis">double-quote</em> context isthe "interpolative" context of Perl, and is supplied by many operatorsthat don't happen to resemble double quotes.)</p><p>Similarly, a reference behaves as a reference when you give it a"dereference" context, but otherwise acts like a simple scalar value.For example, we might say:<blockquote><pre class="programlisting">$fido = new Camel "Amelia";if (not $fido) { die "dead camel"; }$fido-&gt;saddle();</pre></blockquote>Here we create a reference to a Camel object and put it into thevariable <tt class="literal">$fido</tt>.  On the next line, we test <tt class="literal">$fido</tt> as a scalar Booleanto see if it is "true", and we throw an exception (that is, wecomplain) if it is not true, which in this case would mean that the<tt class="literal">new Camel</tt> constructor failed to make a proper Camel object.  But onthe last line, we treat <tt class="literal">$fido</tt> as a reference by asking it to look upthe <tt class="literal">saddle()</tt> method for the object held in <tt class="literal">$fido</tt>, which happensto be a Camel, so Perl looks up the <tt class="literal">saddle()</tt> method for Camelobjects.  More about that later.  For now, just remember that contextis important in Perl because that's how Perl knows what you wantwithout your having to say it explicitly, as many other computerlanguages force you to do.</p><h3 class="sect3">1.2.1.2. Pluralities</h3><a name="INDEX-75"></a><a name="INDEX-76"></a><a name="INDEX-77"></a><a name="INDEX-78"></a><a name="INDEX-79"></a><p>Some kinds of variables hold multiple values that are logicallytied together.  Perl has two types of multivalued variables: arraysand hashes.  In many ways, these behave like scalars--they spring intoexistence with nothing in them when needed, for instance.  But theyare different from scalars in that, when you assign to them, theysupply a <em class="emphasis">list</em> context to the right side of the assignment ratherthan a scalar context.</p><p><a name="INDEX-80"></a><a name="INDEX-81"></a>Arrays and hashes also differ from each other.You'd use an array when you want to look something up by number.  You'duse a hash when you want to look something up by name.  The two conceptsare complementary.  You'll often see people using an array to translatemonth numbers into month names, and a corresponding hash to translatemonth names back into month numbers.  (Though hashes aren't limited toholding only numbers.  You could have a hash that translates month namesto birthstone names, for instance.)</p><h3 class="sect4">1.2.1.2.1. Arrays.</h3><p><a name="INDEX-82"></a>An <em class="emphasis">array</em> is an ordered list of scalars, accessed<a href="#FOOTNOTE-6">[6]</a> bythe scalar's position in the list.  The list may contain numbers, orstrings, or a mixture of both.  (It might also containreferences to subarrays or subhashes.)To assign a list value to an array, you simply group the valuestogether (with a set of parentheses):<blockquote><pre class="programlisting">@home = ("couch", "chair", "table", "stove");</pre></blockquote>Conversely, if you use <tt class="literal">@home</tt> in a list context, such as on the rightside of a list assignment, you get back out the same list you put in. Soyou could set four scalar variables from the array like this:<blockquote><pre class="programlisting">($potato, $lift, $tennis, $pipe) = @home;</pre></blockquote>These are called list assignments.  They logically happen in parallel,so you can swap two variables by saying:<blockquote><pre class="programlisting">($alpha,$omega) = ($omega,$alpha);</pre></blockquote><a name="INDEX-83"></a><a name="INDEX-84"></a>As in C, arrays are zero-based, so while you would talk about the firstthrough fourth elements of the array, you would get to them withsubscripts 0 through 3.<a href="#FOOTNOTE-7">[7]</a> Array subscripts are enclosed in squarebrackets [like this], so if you want to select an individual arrayelement, you would refer to it as <tt class="literal">$home[</tt><em class="replaceable">n</em><tt class="literal">]</tt>, where <em class="replaceable">n</em> is thesubscript (one less than the element number) you want.  See the examplethat follows.  Since the element you are dealing with is a scalar, you alwaysprecede it with a <tt class="literal">$</tt>.<a name="INDEX-85"></a></p><blockquote class="footnote"><a name="FOOTNOTE-6"></a><p>[6] Or keyed,or indexed, or subscripted, or looked up.  Take your pick.</p></blockquote><blockquote class="footnote"><a name="FOOTNOTE-7"></a><p>[7] If this seems odd to you, just thinkof the subscript as an offset, that is, the count of how many arrayelements come before it.  Obviously, the first element doesn't have anyelements before it, and so has an offset of 0.  This is how computersthink.  (We think.)</p></blockquote><p>If you want to assign to one array element at a time, you could writethe earlier assignment as:<blockquote><pre class="programlisting">$home[0] = "couch";$home[1] = "chair";$home[2] = "table";$home[3] = "stove";</pre></blockquote><a name="INDEX-86"></a>Since arrays are ordered, youcan do various useful operations on them, such as the stack operations <tt class="literal">push</tt> and <tt class="literal">pop</tt>.  Astack is, after all, just an ordered list, with a beginning and an end.Especially an end.  Perl regards the end of your array as the top of astack.  (Although most Perl programmers think of an array as horizontal,with the top of the stack on the right.)</p><h3 class="sect4">1.2.1.2.2. Hashes.</h3><p><a name="INDEX-87"></a><a name="INDEX-88"></a><a name="INDEX-89"></a><a name="INDEX-90"></a>A <em class="emphasis">hash</em> is an unordered set of scalars,accessed<a href="#FOOTNOTE-8">[8]</a> by some string valuethat is associated with each scalar.  For this reason hashes are oftencalled <em class="emphasis">associative arrays</em>.  But that's too longfor lazy typists to type, and we talk about them so often that wedecided to name them something short and snappy.  The other reason wepicked the name "hash" is to emphasize the fact that they'redisordered.  (They are, coincidentally, implemented internally using ahash-table lookup, which is why hashes are so fast, and stay so fastno matter how many values you put into them.)  You can't<tt class="literal">push</tt> or <tt class="literal">pop</tt> a hash though,because it doesn't make sense.  A hash has no beginning or end.Nevertheless, hashes are extremely powerful and useful.  Until youstart thinking in terms of hashes, you aren't really thinking in Perl.<a href="ch01_02.htm#perl3-fig-array-and-hash">Figure 1-1</a> shows the ordered elementsof an array and the unordered (but named) elements of a hash.</p><blockquote class="footnote"><a name="FOOTNOTE-8"></a><p>[8] Or keyed, or indexed, or subscripted, orlooked up.  Take your pick.</p></blockquote><a name="perl3-fig-array-and-hash"></a><div class="figure"></div><h4 class="objtitle">Figure 1.1. An array and a hash</h4><p><a name="INDEX-91"></a><a name="INDEX-92"></a><a name="INDEX-93"></a><a name="INDEX-94"></a>Since the keys to a hash are not automatically implied by theirposition, you must supply the key as well as the value when populating ahash. You can still assign a list to it like an ordinary array, but each<em class="emphasis">pair</em> of items in the list will be interpreted as a key and a value.Since we're dealing with pairs of items, hashes use the funny character<tt class="literal">%</tt> to mark hash names.  (If you look carefully at the <tt class="literal">%</tt> character,you can see the key and the value with a slash between them.  It mayhelp to squint.)</p><p>Suppose you wanted to translate abbreviated day names to thecorresponding full names.  You could write the following listassignment:<blockquote><pre class="programlisting">%longday = ("Sun", "Sunday", "Mon", "Monday", "Tue", "Tuesday",            "Wed", "Wednesday", "Thu", "Thursday", "Fri",            "Friday", "Sat", "Saturday");</pre></blockquote><a name="INDEX-95"></a><a name="INDEX-96"></a><a name="INDEX-97"></a>But that's rather difficult to read, so Perl provides the<tt class="literal">=&gt;</tt> (equals sign, greater-than sign) sequence as analternative separator to the comma.  Using this syntactic sugar(and some creative formatting), it is much easier to see which stringsare the keys and which strings are the associated values.<blockquote><pre class="programlisting">%longday = (    "Sun" =&gt; "Sunday",    "Mon" =&gt; "Monday",    "Tue" =&gt; "Tuesday",    "Wed" =&gt; "Wednesday",    "Thu" =&gt; "Thursday",    "Fri" =&gt; "Friday",    "Sat" =&gt; "Saturday",);</pre></blockquote><a name="INDEX-98"></a><a name="INDEX-99"></a><a name="INDEX-100"></a>Not only can you assign a list to a hash, as we did above, but if youmention a hash in list context, it'll convert the hash back to a list ofkey/value pairs, in a weird order.  This is occasionally useful.  Moreoften people extract a list of just the keys, using the (aptly named)<tt class="literal">keys</tt> function. The key list is also unordered, but can easily besorted if desired, using the (aptly named) <tt class="literal">sort</tt> function.  Then youcan use the ordered keys to pull out the corresponding values in theorder you want.</p><p><a name="INDEX-101"></a><a name="INDEX-102"></a><a name="INDEX-103"></a><a name="INDEX-104"></a><a name="INDEX-105"></a>Because hashes are a fancy kind of array, you select an individual hashelement by enclosing the key in braces (those fancy brackets alsoknown as "curlies").  So, for example, if you want to find out thevalue associated with <tt class="literal">Wed</tt> in the hash above, you would use<tt class="literal">$longday{"Wed"}</tt>.  Note again that you are dealing with a scalarvalue, so you use <tt class="literal">$</tt> on the front, not <tt class="literal">%</tt>, which would indicatethe entire hash.</p><p>Linguistically, the relationship encoded in a hash is genitive orpossessive, like the word "of" in English, or like "'s".  The wife <em class="emphasis">of</em>Adam is Eve, so we write:<blockquote><pre class="programlisting">$wife{"Adam"} = "Eve";</pre></blockquote></p><h3 class="sect3">1.2.1.3. Complexities</h3><p>Arrays and hashes are lovely, simple, flat data structures.Unfortunately, the world does not always cooperate with our attempts tooversimplify.  Sometimes you need to build not-so-lovely,not-so-simple, not-so-flat data structures.  Perl lets you do this bypretending that complicated values are really simple ones.  To put itthe other way around, Perl lets you manipulate simple scalar referencesthat happen to refer to complicated arrays and hashes.  We do this allthe time in natural language when we use a simple singular noun like"government" to represent an entity that is completely convoluted andinscrutable.  Among other things.</p><p>To extend our previous example, suppose we want to switch from talkingabout Adam's wife to Jacob's wife.  Now, as it happens, Jacob had fourwives.  (Don't try this at home.)  In trying to represent this in Perl,we find ourselves in the odd situation where we'd like to pretend thatJacob's four wives were really one wife.  (Don't try this at home,either.)  You might think you could write it like this:<blockquote><pre class="programlisting">$wife{"Jacob"} = ("Leah", "Rachel", "Bilhah", "Zilpah");        # WRONG</pre></blockquote><a name="INDEX-106"></a><a name="INDEX-107"></a><a name="INDEX-108"></a><a name="INDEX-109"></a><a name="INDEX-110"></a>But that wouldn't do what you want, because even parentheses and commasare not powerful enough to turn a list into a scalar in Perl.(Parentheses are used for syntactic grouping, and commas for syntacticseparation.)  Rather, you need to tell Perl explicitly that youwant to pretend that a list is a scalar.  It turns out that squarebrackets are powerful enough to do that:<blockquote><pre class="programlisting">$wife{"Jacob"} = ["Leah", "Rachel", "Bilhah", "Zilpah"];        # ok</pre></blockquote>That statement creates an unnamed array and puts a reference to it intothe hash element <tt class="literal">$wife{"Jacob"}</tt>.  So we have a named hashcontaining an unnamed array.  This is how Perl deals with bothmultidimensional arrays and nested data structures.  As with ordinaryarrays and hashes, you can also assign individual elements, like this:<blockquote><pre class="programlisting">$wife{"Jacob"}[0] = "Leah";$wife{"Jacob"}[1] = "Rachel";$wife{"Jacob"}[2] = "Bilhah";$wife{"Jacob"}[3] = "Zilpah";</pre></blockquote><a name="INDEX-111"></a><a name="INDEX-112"></a><a name="INDEX-113"></a><a name="INDEX-114"></a>You can see how that looks like a multidimensional array with onestring subscript and one numeric subscript.  To see something thatlooks more tree-structured, like a nested data structure, suppose wewanted to list not only Jacob's wives but all the sons of each of hiswives.  In this case we want to treat a hash as a scalar.  We can usebraces for that.  (Inside each hash value we'll use square brackets torepresent arrays, just as we did earlier.  But now we have an array in ahash in a hash.)<blockquote><pre class="programlisting">$kids_of_wife{"Jacob"} = {    "Leah"   =&gt; ["Reuben", "Simeon", "Levi", "Judah", "Issachar", "Zebulun"],    "Rachel" =&gt; ["Joseph", "Benjamin"],    "Bilhah" =&gt; ["Dan", "Naphtali"],

⌨️ 快捷键说明

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