📄 ch02_06.htm
字号:
<html><head><title>Scalar Values (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 & Associates, Inc."><meta name="DC.Source" content="" scheme="ISBN"><meta name="DC.Subject.Keyword" content=""><meta name="DC.Title" content="Scalar Values"><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="ch02_05.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0"></a></td><td align="center" valign="top" width="171"><a href="ch02_01.htm">Chapter 2: Bits and Pieces</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></table></div><hr width="515" align="left"><!-- SECTION BODY --><h2 class="sect1">2.6. Scalar Values</h2><p><a name="INDEX-521"></a><a name="INDEX-522"></a><a name="INDEX-523"></a><a name="INDEX-524"></a><a name="INDEX-525"></a><a name="INDEX-526"></a><a name="INDEX-527"></a><a name="INDEX-528"></a>Whether it's named directly or indirectly, and whether it's in avariable, or an array element, or is just a temporary value, a scalaralways contains a single value. This value may be a number, a string,or a reference to another piece of data. Or, there might even be novalue at all, in which case the scalar is said to be<em class="emphasis">undefined</em>. Although we might speak of a scalaras "containing" a number or a string, scalars are typeless: you arenot required to declare your scalars to be of type integer orfloating-point or string or whatever.<a href="#FOOTNOTE-9">[9]</a></p><blockquote class="footnote"><a name="FOOTNOTE-9"></a><p>[9] Future versionsof Perl will allow you to insert <tt class="literal">int</tt>,<tt class="literal">num</tt>, and <tt class="literal">str</tt> type declarations,not to enforce strong typing, but only to give the optimizer hintsabout things that it might not figure out for itself. Generally,you'd only consider doing this in tight code that must run very fast,so we're not going to tell you how to do it yet. Optional types arealso used by the pseudohash mechanism, in which case they can functionas types do in a more strongly typed language. See<a href="ch08_01.htm">Chapter 8, "References"</a> for more.</p></blockquote><p><a name="INDEX-529"></a><a name="INDEX-530"></a>Perl stores strings as sequences of characters, with no arbitrary constraintson length or content. In human terms, you don't have to decide in advancehow long your strings are going to get, and you can include any charactersincluding null bytes within your string. Perl stores numbers as signedintegers if possible, or as double-precision floating-point values inthe machine's native format otherwise. Floating-point values are notinfinitely precise. This is important to remember because comparisonslike <tt class="literal">(10/3 == 1/3*10)</tt> tend to fail mysteriously.</p><p><a name="INDEX-531"></a><a name="INDEX-532"></a><a name="INDEX-533"></a>Perl converts between the various subtypes as needed, so you can treata number as a string or a string as a number, and Perl will do theRight Thing. To convert from string to number, Perl internally usessomething like the C library's <em class="emphasis">atof</em>(3)function. To convert from number to string, it does the equivalent ofan <em class="emphasis">sprintf</em>(3) with a format of<tt class="literal">"%.14g"</tt> on most machines. Improper conversions ofa nonnumeric string like <tt class="literal">foo</tt> to a number count asnumeric 0; these triggerwarnings if you have them enabled, but are silent otherwise. See<a href="ch05_01.htm">Chapter 5, "Pattern Matching"</a>, for examples ofdetecting what sort of data a string holds.</p><p><a name="INDEX-534"></a>Although strings and numbers are interchangeable for nearly all intents,references are a bit different. They're strongly typed, uncastablepointers with built-in reference-counting and destructor invocation. That is,you can use them to create complex data types, including user-defined objects.But they're still scalars, for all that, because no matter how complicateda data structure gets, you often want to treat it as a single value.</p><p><a name="INDEX-535"></a><a name="INDEX-536"></a>By <em class="emphasis">uncastable</em>, we mean that you can't, forinstance, convert a reference to an array into a reference to a hash.References are not castable to other pointer types. However, if youuse a reference as a number or a string, you will get a numeric orstring value, which is guaranteed to retain the uniqueness of thereference even though the "referenceness" of the value is lost whenthe value is copied from the real reference. You can compare suchvalues or extract their type. But you can't do much else with thevalues, since there's no way to convert numbers or strings back intoreferences. Usually, this is not a problem, because Perl doesn'tforce you to do pointer arithmetic--or even allow it. See <a href="ch08_01.htm">Chapter 8, "References"</a> for more on references.</p><h3 class="sect2">2.6.1. Numeric Literals</h3><a name="INDEX-537"></a><a name="INDEX-538"></a><p><a name="INDEX-539"></a>Numeric literals are specified in any of several customary<a href="#FOOTNOTE-10">[10]</a> floating-point or integer formats:<blockquote><pre class="programlisting">$x = 12345; # integer$x = 12345.67; # floating point$x = 6.02e23; # scientific notation$x = 4_294_967_296; # underline for legibility$x = 0377; # octal$x = 0xffff; # hexadecimal$x = 0b1100_0000; # binary</pre></blockquote><a name="INDEX-540"></a><a name="INDEX-541"></a><a name="INDEX-542"></a></p><blockquote class="footnote"><a name="FOOTNOTE-10"></a><p>[10]Customary in Unix culture, that is. If you're from a different culture,welcome to ours!</p></blockquote><p><a name="INDEX-543"></a><a name="INDEX-544"></a><a name="INDEX-545"></a><a name="INDEX-546"></a><a name="INDEX-547"></a><a name="INDEX-548"></a><a name="INDEX-549"></a><a name="INDEX-550"></a>Because Perl uses the comma as a list separator, you cannot use itto separate the thousands in a large number. Perl does allow you touse an underscore character instead. The underscore only works withinliteral numbers specified in your program, not for strings functioningas numbers or data read from somewhere else. Similarly, the leading<tt class="literal">0x</tt> for hexadecimal, <tt class="literal">0b</tt> for binary, and <tt class="literal">0</tt> for octal work onlyfor literals. The automatic conversion of a string to a number does notrecognize these prefixes--you must do an explicit conversion<a href="#FOOTNOTE-11">[11]</a> with the <tt class="literal">oct</tt> function--whichworks for hex and binary numbers, too, as it happens, provided you supplythe <tt class="literal">0x</tt> or <tt class="literal">0b</tt> on the front.</p><blockquote class="footnote"><a name="FOOTNOTE-11"></a><p>[11]Sometimes people think Perl should convert all incoming data for them. But there are far too many decimal numbers with leading zeros inthe world to make Perl do this automatically. For example, the ZipCode for the O'Reilly & Associates office in Cambridge, MA, is <tt class="literal">02140</tt>. The postmaster would get confused if your mailing label program turned<tt class="literal">02140</tt> into <tt class="literal">1120</tt> decimal.</p></blockquote><h3 class="sect2">2.6.2. String Literals</h3><p><a name="INDEX-551"></a><a name="INDEX-552"></a><a name="INDEX-553"></a><a name="INDEX-554"></a><a name="INDEX-555"></a><a name="INDEX-556"></a><a name="INDEX-557"></a>String literals are usually surrounded by either single or doublequotes. They work much like Unix shell quotes: double-quoted stringliterals are subject to backslash and variable interpolation, butsingle-quoted strings are not (except for <tt class="literal">\'</tt> and<tt class="literal">\\</tt>, so that you can embed single quotes andbackslashes into single-quoted strings). If you want to embed anyother backslash sequences such as <tt class="literal">\n</tt> (newline), youmust use the double-quoted form. (Backslash sequences are also knownas <em class="emphasis">escape sequences</em>, because you "escape" thenormal interpretation of characters temporarily.)<a name="INDEX-558"></a></p><p><a name="INDEX-559"></a>A single-quoted string must be separated from a preceding word by aspace because a single quote is a valid--though archaic--character inan identifier. Its use has been replaced by the more visuallydistinct <tt class="literal">::</tt> sequence. That means that<tt class="literal">$main'var</tt> and <tt class="literal">$main::var</tt> are thesame thing, but the second is generally considered easier to read forpeople and programs.</p><p><a name="INDEX-560"></a><a name="INDEX-561"></a>Double-quoted strings are subject to various forms of characterinterpolation, many of which will be familiar to programmers of otherlanguages. These are listed in <a href="ch02_06.htm#perl2-ch-2-tab-4">Table 2-1</a>.</p><a name="perl2-ch-2-tab-4"></a><h4 class="objtitle">Table 2.1. Backslashed Character Escapes</h4><table border="1"><tr><th>Code</th><th>Meaning</th></tr><tr><td><tt class="literal">\n</tt></td><td>Newline (usually LF)</td></tr><tr><td><tt class="literal">\r</tt></td><td>Carriage return (usually CR)</td></tr><tr><td><tt class="literal">\t</tt></td><td>Horizontal tab</td></tr><tr><td><tt class="literal">\f</tt></td><td>Form feed</td></tr><tr><td><tt class="literal">\b</tt></td><td>Backspace<a name="INDEX-562"></a></td></tr><tr><td><tt class="literal">\a</tt></td><td>Alert (bell)<a name="INDEX-563"></a></td></tr><tr><td><tt class="literal">\e</tt></td><td>ESC character<a name="INDEX-564"></a></td></tr><tr><td><tt class="literal">\033</tt></td><td>ESC in octal<a name="INDEX-565"></a></td></tr><tr><td><tt class="literal">\x7f</tt></td><td>DEL in hexadecimal<a name="INDEX-566"></a></td></tr><tr><td><tt class="literal">\cC</tt></td><td>Control-C<a name="INDEX-567"></a></td></tr><tr><td><tt class="literal">\x{263a}</tt></td><td>Unicode (smiley)<a name="INDEX-568"></a></td></tr><tr><td><tt class="literal">\N{</tt><em class="replaceable">NAME</em><tt class="literal">}</tt><a name="INDEX-569"></a></td><td>Named character</td></tr></table><p><a name="INDEX-570"></a>The<tt class="literal">\N{</tt><em class="replaceable">NAME</em><tt class="literal">}</tt>notation is usable only in conjunction with the <tt class="literal">usecharnames</tt> pragma described in <a href="ch31_01.htm">Chapter 31, "Pragmatic Modules"</a>. This allows you to specifycharacter names symbolically, as in <tt class="literal">\N{GREEK SMALL LETTERSIGMA}</tt>, <tt class="literal">\N{greek:Sigma}</tt>, or<tt class="literal">\N{sigma}</tt>--depending on how you call the pragma.See also <a href="ch15_01.htm">Chapter 15, "Unicode"</a>.</p><p><a name="INDEX-571"></a>There are also escape sequences to modify the case or "meta-ness" ofsubsequent characters. See <a href="ch02_06.htm#perl2-ch-2-tab-5">Table 2-2</a>.</p><a name="perl2-ch-2-tab-5"></a><h4 class="objtitle">Table 2.2. Translation Escapes</h4><table border="1"><tr><th>Code</th><th>Meaning</th></tr>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -