📄 ch02_05.htm
字号:
<html><head><title>Scalar Variables (Learning Perl, 3rd Edition)</title><link rel="stylesheet" type="text/css" href="../style/style1.css" /><meta name="DC.Creator" content="Randal L. Schwartz and Tom Phoenix" /><meta name="DC.Format" content="text/xml" scheme="MIME" /><meta name="DC.Language" content="en-US" /><meta name="DC.Publisher" content="O'Reilly & Associates, Inc." /><meta name="DC.Source" scheme="ISBN" content="0596001320L" /><meta name="DC.Subject.Keyword" content="stuff" /><meta name="DC.Title" content="Learning Perl, 3rd Edition" /><meta name="DC.Type" content="Text.Monograph" /></head><body bgcolor="#ffffff"><img alt="Book Home" border="0" src="gifs/smbanner.gif" usemap="#banner-map" /><map name="banner-map"><area shape="rect" coords="1,-2,616,66" href="index.htm" alt="Learning Perl, 3rd Edition" /><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><table width="684" border="0"><tr><td align="left" valign="top" width="228"><a href="ch02_04.htm"><img alt="Previous" border="0" src="../gifs/txtpreva.gif" /></a></td><td align="center" valign="top" width="228"><a href="index.htm"></a></td><td align="right" valign="top" width="228"><a href="ch02_06.htm"><img alt="Next" border="0" src="../gifs/txtnexta.gif" /></a></td></tr></table></div><h2 class="sect1">2.5. Scalar Variables</h2><p>A<em class="emphasis">variable</em><a name="INDEX-176" />is a name for a container that holds one or more values.<a href="#FOOTNOTE-54">[54]</a> The name of the variable stays thesame throughout the program, but the value or values contained inthat variable typically change over and over again throughout theexecution of the program.</p><blockquote class="footnote"><a name="FOOTNOTE-54" /><p>[54]As we'll see, a scalar variable can hold only one value.But other types of variables, such as arrays and hashes, may holdmany values.</p> </blockquote><p>A scalar variable holds a single scalar value, as you'd expect.Scalar variable names begin with a <a name="INDEX-177" />dollar sign followed by whatwe'll call a <em class="emphasis">Perl identifier:</em><a name="INDEX-178" />a letter or underscore, and thenpossibly more letters, or digits, or underscores. Another way tothink of it is that it's made up of alphanumerics andunderscores, but can't start with a digit. Uppercase andlowercase letters are distinct: the variable <tt class="literal">$Fred</tt>is a different variable from <tt class="literal">$fred</tt>. And all of theletters, digits, and underscores are significant, so:</p><blockquote><pre class="code">$a_very_long_variable_that_ends_in_1</pre></blockquote><p> is different from:</p><blockquote><pre class="code">$a_very_long_variable_that_ends_in_2</pre></blockquote><p>Scalar variables in Perl are always referenced with the leading<tt class="literal">$</tt>. In the shell, you use <tt class="literal">$</tt> toget the value, but leave the <tt class="literal">$</tt> off to assign a newvalue. In <em class="emphasis">awk</em> or C, you leave the<tt class="literal">$</tt> off entirely. If you bounce back and forth alot, you'll find yourself typing the wrong things occasionally.This is expected. (Most Perl programmers would recommend that youstop writing shell, <em class="emphasis">awk</em>, and C programs, butthat may not work for you.)</p><a name="lperl3-CHP-2-SECT-5.1" /><div class="sect2"><h3 class="sect2">2.5.1. Choosing Good Variable Names</h3><p>You should generally select variable<a name="INDEX-179" />namesthat mean something regarding the purpose of the variable. Forexample, <tt class="literal">$r</tt> is probably not very descriptive but<tt class="literal">$line_length</tt> is. A variable used for only two orthree lines close together may be called something simple, like<tt class="literal">$n</tt>, but a variable used throughout a programshould probably have a more descriptive name.</p><p>Similarly, properly placed underscores can make a name easier to readand understand, especially if your maintenance programmer has adifferent spoken language background than you have. For example,<tt class="literal">$super_bowl</tt> is a better name than<tt class="literal">$superbowl</tt>, since that last one might look like<tt class="literal">$superb_owl</tt>. Does <tt class="literal">$stopid</tt> mean<tt class="literal">$sto_pid</tt> (storing a process-<span class="acronym">ID</span>of some kind?) or <tt class="literal">$s_to_pid</tt> (converting somethingto a process-<span class="acronym">ID</span>?) or <tt class="literal">$stop_id</tt>(the <span class="acronym">ID</span> for some kind of "stop"object?) or is it just a stopid mispelling?</p><p>Most variable names in our Perl programs are all<a name="INDEX-180" />lowercase, like most of theones we'll see in this book. In a few special cases,<a name="INDEX-181" /><a name="INDEX-182" />capitalization is used. Using all-caps(like <tt class="literal">$ARGV</tt>) generally indicates thatthere's something special about that variable. (But you can getinto an all-out brawl if you choose sides on the<tt class="literal">$underscores_are_cool</tt> versus the<tt class="literal">$giveMeInitialCaps</tt> argument. So be careful.)</p><p>Of course, choosing good or poor names makes no difference to Perl.You <em class="emphasis">could</em> name your program's threemost-important variables <tt class="literal">$OOO000OOO</tt>,<tt class="literal">$OO00OO00</tt>, and <tt class="literal">$O0O0O0O0O</tt> andPerl wouldn't be bothered -- but in that case, please,don't ask us to maintain your code.</p></div><a name="lperl3-CHP-2-SECT-5.2" /><div class="sect2"><h3 class="sect2">2.5.2. Scalar Assignment</h3><p>The most common operation on a scalar variable is<em class="emphasis">assignment</em><a name="INDEX-183" />,which is the way to give a<a name="INDEX-184" /><a name="INDEX-185" /><a name="INDEX-186" />value to a variable. The Perl<a name="INDEX-187" /><a name="INDEX-188" />assignment operator is the equals sign (muchlike other languages), which takes a variable name on the left side,and gives it the value of the expression on the right. For example:</p><blockquote><pre class="code">$fred = 17; # give $fred the value of 17$barney = 'hello'; # give $barney the five-character string 'hello'$barney = $fred + 3; # give $barney the current value of $fred plus 3 (20)$barney = $barney * 2; # $barney is now $barney multiplied by 2 (40)</pre></blockquote><p>Notice that last line uses the <tt class="literal">$barney</tt> variabletwice: once to get its value (on the right side of the equals sign),and once to define where to put the computed expression (on the leftside of the equals sign). This is legal, safe, and in fact, rathercommon. In fact, it's so common that we can write it using aconvenient shorthand, as we'll see in the next section.</p></div><a name="lperl3-CHP-2-SECT-5.3" /><div class="sect2"><h3 class="sect2">2.5.3. Binary Assignment Operators</h3><p>Expressions like <tt class="literal">$fred = $fred + 5</tt> (where the samevariable appears on both sides of an assignment) occur frequentlyenough that Perl (like C and Java) has a shorthand for the operationof altering a<a name="INDEX-189" />variable -- the<em class="emphasis">binary assignmentoperator</em><a name="INDEX-190" />. Nearly allbinary operators that compute avalue have a corresponding binary assignment form with an appendedequals sign. For example, the following two lines are equivalent:</p><blockquote><pre class="code">$fred = $fred + 5; # without the binary assignment operator$fred += 5; # with the binary assignment operator</pre></blockquote><p>These are also equivalent:</p><blockquote><pre class="code">$barney = $barney * 3;$barney *= 3;</pre></blockquote><p>In each case, the operator causes the existing value of the variableto be altered in some way, rather than simply overwriting the valuewith the result of some new expression.</p><p>Another common assignment operator is the <a name="INDEX-191" /><a name="INDEX-192" />string concatenate operator (<tt class="literal">.</tt> ); this gives us an <a name="INDEX-193" /> <a name="INDEX-194" />append operator (<tt class="literal">.=</tt> ):</p><blockquote><pre class="code">$str = $str . " "; # append a space to $str$str .= " "; # same thing with assignment operator</pre></blockquote><p>Nearly all binary operators are valid this way. For example, a<em class="emphasis">raise to the power of</em><a name="INDEX-195" /><a name="INDEX-196" /> <em class="emphasis">operator</em> is writtenas <tt class="literal">**=</tt>. So, <tt class="literal">$fred **= 3</tt> means"raise the number in <tt class="literal">$fred</tt> to the thirdpower, placing the result back in <tt class="literal">$fred</tt>".</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="ch02_04.htm"><img alt="Previous" border="0" src="../gifs/txtpreva.gif" /></a></td><td align="center" valign="top" width="228"><a href="index.htm"><img alt="Home" border="0" src="../gifs/txthome.gif" /></a></td><td align="right" valign="top" width="228"><a href="ch02_06.htm"><img alt="Next" border="0" src="../gifs/txtnexta.gif" /></a></td></tr><tr><td align="left" valign="top" width="228">2.4. Perl's Built-in Warnings</td><td align="center" valign="top" width="228"><a href="index/index.htm"><img alt="Book Index" border="0" src="../gifs/index.gif" /></a></td><td align="right" valign="top" width="228">2.6. Output with print </td></tr></table></div><hr width="684" align="left" /><img alt="Library Navigation Links" border="0" src="../gifs/navbar.gif" usemap="#library-map" /><p><p><font size="-1"><a href="copyrght.htm">Copyright © 2002</a> O'Reilly & 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 + -