📄 ch02_06.htm
字号:
and prints "<tt class="literal">hello world</tt>" followed by a newline on <tt class="literal">STDOUT</tt>. If you leave thefilehandle out, Perl tries to interpret <tt class="literal">hello</tt> as a filehandle,resulting in a syntax error. Because this is so error-prone, somepeople may wish to avoid barewords entirely. The quoting operatorslisted earlier provide many convenient forms, including the <tt class="literal">qw//</tt> "quotewords" construct which nicely quotes a list of space-separated words:<blockquote><pre class="programlisting">@days = qw(Mon Tue Wed Thu Fri);print STDOUT "hello world\n";</pre></blockquote>You can go as far as to outlaw barewords entirely. If you say:<blockquote><pre class="programlisting">use strict 'subs';</pre></blockquote>then any bareword will produce a compile-time error. The restrictionlasts through the end of the enclosing scope. An inner scope maycountermand this by saying:<blockquote><pre class="programlisting">no strict 'subs';</pre></blockquote>Note that the bare identifiers in constructs like:<blockquote><pre class="programlisting">"${verb}able"$days{Feb}</pre></blockquote>are not considered barewords since they're allowed by explicit rulerather than by having "no other interpretation in the grammar".<a name="INDEX-600"></a><a name="INDEX-601"></a></p><p><a name="INDEX-602"></a><a name="INDEX-603"></a>An unquoted name with a trailing double colon, such as<tt class="literal">main::</tt> or <tt class="literal">Dog::</tt>, is alwaystreated as the package name. Perl turns the would-be bareword<tt class="literal">Camel::</tt> into the string "<tt class="literal">Camel</tt>"at compile time, so this usage is not subject to rebuke by<tt class="literal">use strict</tt>.</p><h3 class="sect2">2.6.5. Interpolating Array Values</h3><a name="INDEX-604"></a><a name="INDEX-605"></a><a name="INDEX-606"></a><a name="INDEX-607"></a><a name="INDEX-608"></a><p>Array variables are interpolated into double-quoted strings by joiningall elements of the array with the separator specified in the<tt class="literal">$"</tt> variable<a href="#FOOTNOTE-14">[14]</a> (which contains a space bydefault). The following are equivalent:<blockquote><pre class="programlisting">$temp = join( $", @ARGV );print $temp;print "@ARGV";</pre></blockquote><a name="INDEX-609"></a><a name="INDEX-610"></a><a name="INDEX-611"></a>Within search patterns, which also undergo double-quotish interpolation,there is an unfortunate ambiguity: is <tt class="literal">/$foo[bar]/</tt> to be interpretedas <tt class="literal">/${foo}[bar]/</tt> (where <tt class="literal">[bar]</tt> is a character class for theregular expression) or as <tt class="literal">/${foo[bar]}/</tt> (where <tt class="literal">[bar]</tt> is thesubscript to array <tt class="literal">@foo</tt>)? If <tt class="literal">@foo</tt> doesn't otherwise exist,it's obviously a character class. If <tt class="literal">@foo</tt> exists, Perl takes agood guess about <tt class="literal">[bar]</tt>, and is almost always right.<a href="#FOOTNOTE-15">[15]</a> If it does guess wrong,or if you're just plain paranoid, you can force the correctinterpretation with braces as shown earlier. Even if you're merelyprudent, it's probably not a bad idea.</p><blockquote class="footnote"><a name="FOOTNOTE-14"></a><p>[14]<tt class="literal">$LIST_SEPARATOR</tt> if you use the English modulebundled with Perl.</p></blockquote><blockquote class="footnote"><a name="FOOTNOTE-15"></a><p>[15]The guesser is too boring to describe in full, but basically takesa weighted average of all the things that look like character classes(<tt class="literal">a-z</tt>, <tt class="literal">\w</tt>, initial <tt class="literal">^</tt>) versus things that look like expressions(variables or reserved words).</p></blockquote><h3 class="sect2">2.6.6. "Here" Documents</h3><a name="INDEX-612"></a><a name="INDEX-613"></a><a name="INDEX-614"></a><a name="INDEX-615"></a><a name="INDEX-616"></a><a name="INDEX-617"></a><a name="INDEX-618"></a><p>A line-oriented form of quoting is based on the Unix shell's<em class="emphasis">here-document</em> syntax. It's line-oriented in thesense that the delimiters are lines rather than characters. Thestarting delimiter is the current line, and the terminating delimiteris a line consisting of the string you specify. Following a<tt class="literal"><<</tt>, you specify the string to terminate thequoted material, and all lines following the current line down to butnot including the terminating line are part of the string. Theterminating string may be either an identifier (a word) or some quotedtext. If quoted, the type of quote determines the treatment of thetext, just as it does in regular quoting. An unquoted identifierworks as though it were in double quotes. A backslashed identifierworks as though it were in single quotes (for compatibility with shellsyntax). There must be no space between the<tt class="literal"><<</tt> and an unquoted identifier, althoughwhitespace is permitted if you specify a quoted string instead of thebare identifier. (If you insert a space, it will be treated as a nullidentifier, which is valid but deprecated, and matches the first blankline--see the first <tt class="literal">Hurrah!</tt> example below.) Theterminating string must appear by itself, unquoted and with no extrawhitespace on either side, on the terminating line.<blockquote><pre class="programlisting">print <<EOF; # same as earlier exampleThe price is $Price.EOFprint <<"EOF"; # same as above, with explicit quotesThe price is $Price.EOFprint <<'EOF'; # single-quoted quoteAll things (e.g. a camel's journey throughA needle's eye) are possible, it's true.But picture how the camel feels, squeezed outIn one long bloody thread, from tail to snout. -- C.S. LewisEOFprint << x 10; # print next line 10 timesThe camels are coming! Hurrah! Hurrah!print <<"" x 10; # the preferred way to write thatThe camels are coming! Hurrah! Hurrah!print <<`EOC`; # execute commandsecho hi thereecho lo thereEOCprint <<"dromedary", <<"camelid"; # you can stack themI said bactrian.dromedaryShe said llama.camelidfunkshun(<<"THIS", 23, <<'THAT'); # doesn't matter if they're in parensHere's a lineor two.THISAnd here's another.THAT</pre></blockquote>Just don't forget that you have to put a semicolon on the end to finishthe statement, because Perl doesn't know you're not going to try to do this:<blockquote><pre class="programlisting">print <<'odd'2345odd + 10000; # prints 12345</pre></blockquote><a name="INDEX-619"></a><a name="INDEX-620"></a>If you want your here docs to be indented with the rest of the code,you'll need to remove leading whitespace from each line manually:<blockquote><pre class="programlisting">($quote = <<'QUOTE') =~ s/^\s+//gm; The Road goes ever on and on, down from the door where it began.QUOTE</pre></blockquote>You could even populate an array with the lines of a here document asfollows:<blockquote><pre class="programlisting">@sauces = <<End_Lines =~ m/(\S.*\S)/g; normal tomato spicy tomato green chile pesto white wineEnd_Lines</pre></blockquote></p><h3 class="sect2">2.6.7. V-String Literals</h3><p><a name="INDEX-621"></a><a name="INDEX-622"></a><a name="INDEX-623"></a><a name="INDEX-624"></a>A literal that begins with a <tt class="literal">v</tt> and is followed by one or moredot-separated integers is treated as a string literal composed ofcharacters with the specified ordinal values:<blockquote><pre class="programlisting">$crlf = v13.10; # ASCII carriage return, line feed</pre></blockquote>These are called <em class="emphasis">v-strings</em>, short for "vector strings" or "versionstrings" or anything else you can think of that starts with "v" anddeals with lists of integers. They provide an alternate and morelegible way to construct strings when you want to specify the numericvalues of each character. Thus, <tt class="literal">v1.20.300.4000</tt> is a more winsome way toproduce the same string value as any of:<blockquote><pre class="programlisting">"\x{1}\x{14}\x{12c}\x{fa0}"pack("U*", 1, 20, 300, 4000)chr(1) . chr(20) . chr(300) . chr(4000)</pre></blockquote>If such a literal has two or more dots (three or more integers), theleading <tt class="literal">v</tt> may be omitted.<blockquote><pre class="programlisting">print v9786; # prints UTF-8 encoded SMILEY, "\x{263a}"print v102.111.111; # prints "foo"print 102.111.111; # same thinguse 5.6.0; # require a particular Perl version (or later)$ipaddr = 204.148.40.9; # the IPv4 address of oreilly.com</pre></blockquote>V-strings are useful for representing IP address and version numbers.In particular, since characters can have an ordinal value larger than255 these days, v-strings provide a way to represent version numbers ofany size that can be correctly compared with a simple stringcomparison.</p><p>Version numbers and IP addresses stored in v-strings are not humanreadable, since the individual integers are stored as arbitrarycharacters. To produce something legible, use the<tt class="literal">v</tt> flag in a <tt class="literal">printf</tt> mask, like<tt class="literal">"%vd"</tt>, as described under<tt class="literal">sprintf</tt> in <a href="ch29_01.htm">Chapter 29, "Functions"</a>.For more on Unicode strings, see <a href="ch15_01.htm">Chapter 15, "Unicode"</a>and the <tt class="literal">use bytes</tt> pragma in<a href="ch31_01.htm">Chapter 31, "Pragmatic Modules"</a>; for comparing versionstrings using string comparison operators, see <tt class="literal">$^V</tt> in <a href="ch28_01.htm">Chapter 28, "Special Names"</a>; and for representing IPv4addresses, see <tt class="literal">gethostbyaddr</tt> in<a href="ch29_01.htm">Chapter 29, "Functions"</a>.</p><h3 class="sect2">2.6.8. Other Literal Tokens</h3><a name="INDEX-625"></a><a name="INDEX-626"></a><a name="INDEX-627"></a><a name="INDEX-628"></a><a name="INDEX-629"></a><a name="INDEX-630"></a><a name="INDEX-631"></a><a name="INDEX-632"></a><a name="INDEX-633"></a><a name="INDEX-634"></a><p>You should consider any identifier that both begins and ends with adouble underscore to be reserved for special syntactic use by Perl.Two such special literals are <tt class="literal">__LINE__</tt> and <tt class="literal">__FILE__</tt>, whichrepresent the current line number and filename at that point in yourprogram. They may only be used as separate tokens; they will not beinterpolated into strings. Likewise, <tt class="literal">__PACKAGE__</tt> is the name ofthe package the current code is being compiled into. If there is nocurrent package (due to an empty <tt class="literal">package;</tt> directive),<tt class="literal">__PACKAGE__</tt> is the undefined value. The token <tt class="literal">__END__</tt> (oralternatively, a Control-D or Control-Z character) may be used toindicate the logical end of the script before the real end-of-file.Any following text is ignored, but may be read via the <tt class="literal">DATA</tt>filehandle.<a name="INDEX-635"></a><a name="INDEX-636"></a></p><p><a name="INDEX-637"></a> The <tt class="literal">__DATA__</tt> tokenfunctions similarly to the <tt class="literal">__END__</tt> token, but opensthe <tt class="literal">DATA</tt> filehandle within the current package'snamespace, so that files you <tt class="literal">require</tt> can each havetheir own <tt class="literal">DATA</tt> filehandles open simultaneously.For more information, see <tt class="literal">DATA</tt> in<a href="ch28_01.htm">Chapter 28, "Special Names"</a>.</p><a name="INDEX-638"></a><!-- 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="ch02_05.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="ch02_07.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0"></a></td></tr><tr><td align="left" valign="top" width="172">2.5. Names</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">2.7. Context</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 © 2001</a> O'Reilly & 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 + -