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

📄 ch01_05.htm

📁 编程珍珠,里面很多好用的代码,大家可以参考学习呵呵,
💻 HTM
📖 第 1 页 / 共 2 页
字号:
<html><head><title>Operators (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 &amp; Associates, Inc."><meta name="DC.Source" content="" scheme="ISBN"><meta name="DC.Subject.Keyword" content=""><meta name="DC.Title" content="Operators"><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="ch01_04.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0"></a></td><td align="center" valign="top" width="171"><a href="ch01_01.htm">Chapter 1: An Overview of Perl</a></td><td align="right" valign="top" width="172"><a href="ch01_06.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">1.5. Operators</h2><p><a name="INDEX-190"></a><a name="INDEX-191"></a>As we alluded to earlier, Perl is also a mathematical language.  This istrue at several levels, from low-level bitwise logical operations, upthrough number and set manipulation, on up to larger predicates andabstractions of various sorts.  And as we all know from studying math inschool, mathematicians love strange symbols.  What's worse, computerscientists have come up with their own versions of these strangesymbols.  Perl has a number of these strange symbols too, but takeheart, most are borrowed directly from C, FORTRAN, <em class="emphasis">sed</em>(1) or<em class="emphasis">awk</em>(1), so they'll at least be familiar to users of those languages.</p><p>The rest of you can take comfort in knowing that, by learning all thesestrange symbols in Perl, you've given yourself a head start on allthose other strange languages.</p><p><a name="INDEX-192"></a><a name="INDEX-193"></a><a name="INDEX-194"></a><a name="INDEX-195"></a><a name="INDEX-196"></a>Perl's built-in operators may be classified by number of operands intounary, binary, and trinary (or ternary) operators.  They may beclassified by whether they're prefix operators (which go in front oftheir operands) or infix operators (which go in between theiroperands).  They may also be classified by the kinds of objects theywork with, such as numbers, strings, or files.  Later, we'll give you atable of all the operators, but first here are some handy ones to get youstarted.</p><h3 class="sect2">1.5.1. Some Binary Arithmetic Operators</h3><p><a name="INDEX-197"></a></p><p>Arithmetic operators do what you would expect from learning themin school.  They perform some sort of mathematical function on numbers.For example:</p><a name="perl3-tab-over-math"></a><table border="1"><tr><th>Example</th><th>Name</th><th>Result</th></tr><tr><td><tt class="literal">$a + $b</tt></td><td>Addition</td><td>Sum of <tt class="literal">$a</tt> and <tt class="literal">$b</tt><a name="INDEX-198"></a></td></tr><tr><td><tt class="literal">$a * $b</tt></td><td>Multiplication</td><td>Product of <tt class="literal">$a</tt> and <tt class="literal">$b</tt><a name="INDEX-199"></a></td></tr><tr><td><tt class="literal">$a % $b</tt></td><td>Modulus</td><td>Remainder of <tt class="literal">$a</tt> divided by <tt class="literal">$b</tt></td></tr><tr><td><tt class="literal">$a ** $b</tt></td><td>Exponentiation</td><td><tt class="literal">$a</tt> to the power of <tt class="literal">$b</tt></td></tr></table><p><a name="INDEX-200"></a><a name="INDEX-201"></a>Yes, we left out subtraction and division--we suspect you can figureout how they should work.  Try them and see if you're right.  (Or cheatand look in <a href="ch03_01.htm">Chapter 3, "Unary and Binary Operators"</a>.)  Arithmetic operators areevaluated in the order your math teacher taught you (exponentiationbefore multiplication; multiplication before addition).  You canalways use parentheses to make it come out differently.</p><h3 class="sect2">1.5.2. String Operators</h3><p><a name="INDEX-202"></a><a name="INDEX-203"></a><a name="INDEX-204"></a><a name="INDEX-205"></a><a name="INDEX-206"></a></p><p>There is also an "addition" operator for strings that performsconcatenation (that is, joining strings end to end). Unlike some languages thatconfuse this with numeric addition, Perl defines a separate operator(<tt class="literal">.</tt>) for string concatenation:<blockquote><pre class="programlisting">$a = 123;$b = 456;print $a + $b;     # prints 579print $a . $b;     # prints 123456</pre></blockquote><a name="INDEX-207"></a><a name="INDEX-208"></a><a name="INDEX-209"></a><a name="INDEX-210"></a></p><p><a name="INDEX-211"></a><a name="INDEX-212"></a><a name="INDEX-213"></a>There's also a "multiply" operator for strings, called the<em class="emphasis">repeat</em> operator.  Again, it's a separate operator (<tt class="literal">x</tt>) to keep itdistinct from numeric multiplication:<blockquote><pre class="programlisting">$a = 123;$b = 3;print $a * $b;     # prints 369print $a x $b;     # prints 123123123</pre></blockquote>These string operators bind as tightly as their corresponding arithmeticoperators.  The repeat operator is a bit unusual in taking a string forits left argument but a number for its right argument.  Note also howPerl is automatically converting from numbers to strings. You could haveput all the literal numbers above in quotes, and it would still haveproduced the same output.  Internally though, it would have beenconverting in the opposite direction (that is, from strings to numbers).</p><p><a name="INDEX-214"></a><a name="INDEX-215"></a>A couple more things to think about.  String concatenation is alsoimplied by the interpolation that happens in double-quoted strings.  And whenyou print out a list of values, you're also effectively concatenatingstrings.  Sothe following three statements produce the same output:<blockquote><pre class="programlisting">print $a . ' is equal to ' . $b . ".\n";    # dot operatorprint $a, ' is equal to ', $b, ".\n";       # listprint "$a is equal to $b.\n";               # interpolation</pre></blockquote>Which of these you use in any particular situation is entirely up toyou.  (But bear in mind that interpolation is often the most readable.)</p><p>The <tt class="literal">x</tt> operator may seem relatively worthless at first glance, but itis quite useful at times, especially for things like this:<blockquote><pre class="programlisting">print "-" x $scrwid, "\n";</pre></blockquote>which draws a line across your screen, presuming <tt class="literal">$scrwid</tt> containsyour screen width, and not your screw identifier.</p><h3 class="sect2">1.5.3. Assignment Operators</h3><p><a name="INDEX-216"></a><a name="INDEX-217"></a><a name="INDEX-218"></a>Although it's not exactly a mathematical operator, we've already madeextensive use of the simple assignment operator, <tt class="literal">=</tt>.  Try to rememberthat <tt class="literal">=</tt> means "gets set to" rather than "equals".  (There is also amathematical equality operator <tt class="literal">==</tt> that means "equals", and if youstart out thinking about the difference between them now, you'll saveyourself a lot of headache later.  The <tt class="literal">==</tt> operator is like a functionthat returns a Boolean value, while <tt class="literal">=</tt> is more like a procedure thatis evaluated for the side effect of modifying a variable.)</p><p><a name="INDEX-219"></a><a name="INDEX-220"></a>Like the operators described earlier, assignment operators are binary infixoperators, which means they have an operand on either side of theoperator.  The right operand can be any expression you like, but theleft operand must be a valid <em class="emphasis">lvalue</em> (which, when translated toEnglish, means a valid storage location like a variable, or a locationin an array).  The most common assignment operator is simple assignment.It determines the value of the expression on its right side, and then setsthe variable on the left side to that value:<blockquote><pre class="programlisting">$a = $b;$a = $b + 5;$a = $a * 3;</pre></blockquote>Notice the last assignment refers to the same variable twice; once forthe computation, once for the assignment.  There's nothing wrong withthat, but it's a common enough operation that there's a shortcut for it(borrowed from C).  If you say:<blockquote><pre class="programlisting">lvalue operator= expression</pre></blockquote>it is evaluated as if it were:<blockquote><pre class="programlisting">lvalue = lvalue operator expression</pre></blockquote>except that the lvalue is not computed twice.  (This only makes adifference if evaluation of the lvalue has side effects.  But when it<em class="emphasis">does</em> make a difference, it usually does what you want.  So don'tsweat it.)</p><p>So, for example, you could write the previous example as:<blockquote><pre class="programlisting">$a *= 3;</pre></blockquote>which reads "multiply <tt class="literal">$a</tt> by 3".  You can do this with almost anybinary operator in Perl, even some that you can't do it with in C:<blockquote><pre class="programlisting">$line .= "\n";  # Append newline to $line.$fill x= 80;    # Make string $fill into 80 repeats of itself.$val ||= "2";   # Set $val to 2 if it isn't already "true".</pre></blockquote>Line 6 of our Average Example<a href="#FOOTNOTE-16">[16]</a> contains two string concatenations, one ofwhich is an assignment operator.  And line 14 contains a <tt class="literal">+=</tt>.</p><blockquote class="footnote"><a name="FOOTNOTE-16"></a><p>[16]Thought we'd forgotten it,didn't you?</p></blockquote><p><a name="INDEX-221"></a><a name="INDEX-222"></a>Regardless of which kind of assignment operator you use, the finalvalue of the variable on the left is returned as the value of theassignment as a whole.<a href="#FOOTNOTE-17">[17]</a> This will not surprise C programmers,who will already know how to use this idiom to zero out variables:<blockquote><pre class="programlisting">$a = $b = $c = 0;</pre></blockquote>You'll also frequently see assignment used as the condition of a <tt class="literal">while</tt>loop, as in line 4 of our average example.</p><blockquote class="footnote"><a name="FOOTNOTE-17"></a><p>[17] This is unlike, say, Pascal, in whichassignment is a statement and returns no value.  We said earlier thatassignment is like a procedure, but remember that in Perl, evenprocedures return values.</p></blockquote><p>What <em class="emphasis">will</em> surprise C programmers is thatassignment in Perl returns the actual variable as an lvalue, so thatyou can modify the same variable more than once in a statement.  Forinstance, you could say:<blockquote><pre class="programlisting">($temp -= 32) *= 5/9;</pre></blockquote>to do an in-place conversion from Fahrenheit to Celsius.This is also why earlier in this chapter we could say:<blockquote><pre class="programlisting">chop($number = &lt;STDIN&gt;);</pre></blockquote>and have it chop the final value of <tt class="literal">$number</tt>.  Generally speaking, youcan use this feature whenever you want to copy something and at the sametime do something else with it.<a name="INDEX-223"></a><a name="INDEX-224"></a><a name="INDEX-225"></a></p><h3 class="sect2">1.5.4. Unary Arithmetic Operators</h3><p><a name="INDEX-226"></a><a name="INDEX-227"></a><a name="INDEX-228"></a><a name="INDEX-229"></a><a name="INDEX-230"></a><a name="INDEX-231"></a><a name="INDEX-232"></a>As if <tt class="literal">$variable += 1</tt> weren't short enough, Perl borrows from C aneven shorter way to increment a variable.  The autoincrement (andautodecrement) operators simply add (or subtract) one from the value ofthe variable.  They can be placed on either side of the variable,depending on when you want them to be evaluated:</p><a name="perl3-tab-over-crement"></a><table border="1"><tr><th>Example</th><th>Name</th><th>Result</th></tr><tr><td><tt class="literal">++$a, $a++</tt></td><td>Autoincrement</td><td>Add 1 to <tt class="literal">$a</tt></td></tr><tr><td><tt class="literal">--$a, $a--</tt></td><td>Autodecrement</td><td>Subtract 1 from <tt class="literal">$a</tt></td></tr></table><p><a name="INDEX-233"></a><a name="INDEX-234"></a>

⌨️ 快捷键说明

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