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

📄 ch04_02.htm

📁 by Randal L. Schwartz and Tom Phoenix ISBN 0-596-00132-0 Third Edition, published July 2001. (See
💻 HTM
📖 第 1 页 / 共 2 页
字号:
<p><tt class="literal">qr//</tt></p></td><td><p>Pattern</p></td><td><p>Yes</p></td></tr><tr><td><p><tt class="literal">//</tt></p></td><td><p><tt class="literal">m//</tt></p></td><td><p>Pattern match</p></td><td><p>Yes</p></td></tr><tr><td><p><tt class="literal">s///</tt></p></td><td><p><tt class="literal">s///</tt></p></td><td><p>Substitution</p></td><td><p>Yes</p></td></tr><tr><td><p><tt class="literal">y///</tt></p></td><td><p><tt class="literal">tr///</tt></p></td><td><p>Translation</p></td><td><p>No</p></td></tr></table><p></div><a name="perlnut2-CHP-4-SECT-2.3" /><div class="sect2"><h3 class="sect2">4.2.3. Here Documents</h3><p><a name="INDEX-231" /><a name="INDEX-232" />A line-oriented form of quoting is based onthe Unix shell "here-document"syntax. Following a <tt class="literal">&lt;&lt;</tt>, you specify a stringto terminate the quoted material, and all lines following the currentline down to the terminating string are the value of the item. Thisis of particular importance if you're trying toprint something like HTML that would be cleaner to print as a chunkinstead of as individual lines. For example:</p><blockquote><pre class="code">#!/usr/local/bin/perl -wmy $Price = 'right';    print &lt;&lt;"EOF";The price is $Price.EOF</pre></blockquote><p>The terminating string does not have to be quoted. For example, theprevious example could have been written as:</p><blockquote><pre class="code">#!/usr/local/bin/perl -wmy $Price = 'right';    print &lt;&lt;EOF;The price is $Price.EOF</pre></blockquote><p>You can assign here documents to a string: </p><blockquote><pre class="code">my $assign_this_heredoc =&lt;&lt; "EOS";This string is assigned to $whatever.EOS</pre></blockquote><p>You can use a here document to execute commands: </p><blockquote><pre class="code">#!/usr/local/bin/perl -wprint &lt;&lt;`CMD`;ls -lCMD</pre></blockquote><p>You can stack here documents: </p><blockquote><pre class="code">#!/usr/local/bin/perl -wprint &lt;&lt;"joe", &lt;&lt;"momma"; # You can stack themI said foo.joeI said bar.momma</pre></blockquote><p>One caveat about here documents: you may have noticed in each ofthese examples that the quoted text is always left-justified.That's because any whitespace used for indentationwill be included in the string. For example:</p><blockquote><pre class="code">#!/usr/local/bin/perl -wprint &lt;&lt;"    INDENTED";    Same old, same old.    INDENTED</pre></blockquote><p>Although you can use a trick of including whitespace in theterminating tag to keep it indented (as we did here), the stringitself will have the whitespace embedded&#x2014;in this case, it willbe <tt class="literal">Same old, same old.</tt>.</p></div><a name="perlnut2-CHP-4-SECT-2.4" /><div class="sect2"><h3 class="sect2">4.2.4. Lists</h3><p><a name="INDEX-233" /><a name="INDEX-234" />A list is an ordered group of scalarvalues. A literal list can be composed as a comma-separated list ofvalues contained in parentheses, for example:</p><blockquote><pre class="code">(1,2,3)                  # Array of three values 1, 2, and 3("one","two","three")    # Array of three values "one", "two", and "three"</pre></blockquote><p>The generic form of list creation uses the quoting operator<tt class="literal">qw//</tt> to contain a list of values separated bywhitespace:</p><blockquote><pre class="code">qw/snap crackle pop/</pre></blockquote><p>With the quoting operators, you're not limited to<tt class="literal">//</tt> when you use one of the operators. You can usejust about any character you want. The following is exactly the sameas the example above:</p><blockquote><pre class="code">qw!snap crackle pop!</pre></blockquote><p>It's important that you remember not to use anydelimiters except whitespace with <tt class="literal">qw//</tt>. If you do,these delimiters will be handled as list members:</p><blockquote><pre class="code">@foods = qw/fish, beef, lettuce, cat, apple/; # EL WRONG-O!foreach (@foods) {    print $_; # Prints fish and then a literal comma, etc.}</pre></blockquote></div><a name="perlnut2-CHP-4-SECT-2.5" /><div class="sect2"><h3 class="sect2">4.2.5. Variables</h3><p><a name="INDEX-235" />Avariable always begins with the character that identifies its type:<tt class="literal">$</tt>, <tt class="literal">@</tt>, or <tt class="literal">%</tt>.Most of the variable names you create can begin with a letter orunderscore, followed by any combination of letters, digits, orunderscores, up to 255 characters in length. Upper- and lowercaseletters are distinct. Variable names that begin with a digit cancontain only digits, and variable names that begin with a characterother than an alphanumeric or underscore can contain only thatcharacter. The latter forms are usually predefined variables in Perl,so it is best to name your variables beginning with a letter orunderscore.</p><p><a name="INDEX-236" />Variables havethe <tt class="literal">undef</tt> value before they are first assigned orwhen they become "empty." Forscalar variables, <tt class="literal">undef</tt> evaluates to<tt class="literal">0</tt> when used as a number, and a zero-length, emptystring ("") when used as a string.</p><p><a name="INDEX-237" /><a name="INDEX-238" />Simple variable assignment uses theassignment operator (<tt class="literal">=</tt>) with the appropriate data.For example:</p><blockquote><pre class="code">$age = 26;                # Assigns 26 to $age@date = (8, 24, 70);      # Assigns the three-element list to @date%fruit = ('apples', 3, 'oranges', 6);  # Assigns the list elements to %fruit in key/value pairs</pre></blockquote><p><a name="INDEX-239" /><a name="INDEX-240" />Scalar variables are always namedwith an initial <tt class="literal">$</tt>, even when referring to a scalarvalue that is part of an array or hash.</p><p><a name="INDEX-241" /><a name="INDEX-242" />Everyvariable type has its own namespace. You can, without fear ofconflict, use the same name for a scalar variable, an array, or ahash (or, for that matter, a filehandle, a subroutine name, or alabel). This means that <tt class="literal">$foo</tt> and<tt class="literal">@foo</tt> are two different variables. It also meansthat <tt class="literal">$foo[1]</tt> is an element of<tt class="literal">@foo</tt>, not a part of <tt class="literal">$foo</tt>.</p><a name="perlnut2-CHP-4-SECT-2.5.1" /><div class="sect3"><h3 class="sect3">4.2.5.1. Arrays</h3><p><a name="INDEX-243" /><a name="INDEX-244" /><a name="INDEX-245" /><a name="INDEX-246" />Anarray is a variable that stores an ordered list of scalar values.Arrays are preceded by an "at" sign(<tt class="literal">@</tt>).</p><blockquote><pre class="code">@numbers = (1,2,3);        # Set the array @numbers to (1,2,3)</pre></blockquote><p>To refer to a single element of an array, use the dollar sign(<tt class="literal">$</tt>) with the variable name (it'sa scalar), followed by the index of the element in square brackets(the <em class="emphasis">subscript operator</em>). Array elements arenumbered starting at 0. Negative indexes count backwards from thelast element in the list (i.e., -1 refers to the last element of thelist). For example, in this list:</p><blockquote><pre class="code">@date = (8, 24, 70);</pre></blockquote><p><tt class="literal">$date[2]</tt> is the value of the third element, 70.</p></div><a name="perlnut2-CHP-4-SECT-2.5.2" /><div class="sect3"><h3 class="sect3">4.2.5.2. Hashes</h3><p><a name="INDEX-247" /><a name="INDEX-248" /><a name="INDEX-249" /><a name="INDEX-250" /><a name="INDEX-251" />A hash is a set of key/valuepairs. Hashes are preceded by a percent sign (<tt class="literal">%</tt>).To refer to a single element of a hash, you use the hash variablename followed by the "key"associated with the value in braces. For example, the hash:</p><blockquote><pre class="code">%fruit = ('apples', 3, 'oranges', 6);</pre></blockquote><p>has two values (in key/value pairs). If you want to get the valueassociated with the key <tt class="literal">apples</tt>, you use<tt class="literal">$fruit{'apples'}</tt>.</p><p><a name="INDEX-252" /><a name="INDEX-253" />It is oftenmore readable to use the <tt class="literal">=&gt;</tt> operator indefining key/value pairs. The <tt class="literal">=&gt;</tt> operator issimilar to a comma, but it's more visuallydistinctive and quotes any bare identifiers to the left of it:</p><blockquote><pre class="code">%fruit = (    apples  =&gt; 3,    oranges =&gt; 6);</pre></blockquote></div></div><a name="perlnut2-CHP-4-SECT-2.6" /><div class="sect2"><h3 class="sect2">4.2.6. Scalar and List Contexts</h3><p><a name="INDEX-254" /><a name="INDEX-255" /><a name="INDEX-256" /><a name="INDEX-257" />Everyoperation that you invoke in a Perl script is evaluated in a specificcontext, and how that operation behaves may depend on the context itis being called in. There are two major contexts:<em class="emphasis">scalar</em> and <em class="emphasis">list</em>. Alloperators know which context they are in, and some return lists incontexts wanting a list and scalars in contexts wanting a scalar. Forexample, the <tt class="literal">localtime</tt> function returns anine-element list in list context:</p><blockquote><pre class="code">($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime( );</pre></blockquote><p>But in a scalar context, <tt class="literal">localtime</tt> returns thenumber of seconds since January 1, 1970:</p><blockquote><pre class="code">$now = localtime( );</pre></blockquote><p>Statements that look confusing are easy to evaluate by identifyingthe proper context. For example, assigning what is commonly a listliteral to a scalar variable:</p><blockquote><pre class="code">$a = (2, 4, 6, 8);</pre></blockquote><p>gives <tt class="literal">$a</tt> the value 8. The context forces the rightside to evaluate to a scalar, and the action of the comma operator inthe expression (in the scalar context) returns the value farthest tothe right.</p><p>Another type of statement that might be confusing is the evaluationof an array or hash variable as a scalar. For example:</p><blockquote><pre class="code">$b = @c;</pre></blockquote><p>When an array variable is evaluated as a scalar, the number ofelements in the array is returned. This type of evaluation is usefulfor finding the number of elements in an array. The special<tt class="literal">$#</tt><em class="replaceable"><tt>array</tt></em> form of anarray value returns the index of the last member of the list (oneless than the number of elements).</p><p>If necessary, you can force a scalar context in the middle of a list<a name="INDEX-258" />byusing the <tt class="literal">scalar</tt> function.</p></div><a name="perlnut2-CHP-4-SECT-2.7" /><div class="sect2"><h3 class="sect2">4.2.7. Declarations and Scope</h3><p><a name="INDEX-259" /><a name="INDEX-260" /><a name="INDEX-261" />In Perl, only subroutines andformats require explicit declaration. Variables (and similarconstructs) are automatically created when they are first assigned.</p><p>Variable declaration comes into play when you need to limit the scopeof a variable's use. You can do this in two ways:</p><dl><dt><i><em class="emphasis">Dynamic scoping</em> </i></dt><dd><a name="INDEX-262" />Createstemporary objects within a scope. Dynamically scoped constructs arevisible globally, but take action only within their defined scopes.Dynamic scoping applies to variables declared with<tt class="literal">local</tt>.</p></dd><dt><i><em class="emphasis">Lexical scoping</em> </i></dt><dd><a name="INDEX-263" /><a name="INDEX-264" />Creates private constructs that arevisible only within their scopes. The most frequently seen form oflexically scoped declaration is the declaration of<tt class="literal">my</tt> variables.</p></dd></dl><p><a name="INDEX-265" /><a name="INDEX-266" />Therefore, we can say that a<tt class="literal">local</tt> variable is <em class="emphasis">dynamicallyscoped</em>, whereas a <tt class="literal">my</tt> variable is<em class="emphasis">lexically scoped</em>. Dynamically scoped variablesare visible to functions called from within the block in which theyare declared. Lexically scoped variables, on the other hand, aretotally hidden from the outside world, including any calledsubroutines, unless they are declared within the same scope. See <a href="ch04_07.htm#perlnut2-CHP-4-SECT-7">Section 4.7, "Subroutines"</a> later in thischapter for further discussion.</p></div><hr width="684" align="left" /><div class="navbar"><table width="684" border="0"><tr><td align="left" valign="top" width="228"><a href="ch04_01.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0" /></a></td><td align="center" valign="top" width="228"><a href="index.htm"><img src="../gifs/txthome.gif" alt="Home" border="0" /></a></td><td align="right" valign="top" width="228"><a href="ch04_03.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0" /></a></td></tr><tr><td align="left" valign="top" width="228">4. The Perl Language</td><td align="center" valign="top" width="228"><a href="index/index.htm"><img src="../gifs/index.gif" alt="Book Index" border="0" /></a></td><td align="right" valign="top" width="228">4.3. Statements</td></tr></table></div><hr width="684" align="left" /><img src="../gifs/navbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links" /><p><p><font size="-1"><a href="copyrght.htm">Copyright &copy; 2002</a> O'Reilly &amp; Associates. All rights reserved.</font></p><map name="library-map"><area shape="rect" coords="1,0,85,94" href="../index.htm"><area shape="rect" coords="86,1,178,103" href="../lwp/index.htm"><area shape="rect" coords="180,0,265,103" href="../lperl/index.htm"><area shape="rect" coords="267,0,353,105" href="../perlnut/index.htm"><area shape="rect" coords="354,1,446,115" href="../prog/index.htm"><area shape="rect" coords="448,0,526,132" href="../tk/index.htm"><area shape="rect" coords="528,1,615,119" href="../cookbook/index.htm"><area shape="rect" coords="617,0,690,135" href="../pxml/index.htm"></map></body></html>

⌨️ 快捷键说明

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