📄 ch01_02.htm
字号:
<html><head><title>Natural and Artificial Languages (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="Natural and Artificial Languages"><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_01.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_03.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.2. Natural and Artificial Languages</h2><a name="INDEX-21"></a><a name="INDEX-22"></a><a name="INDEX-23"></a><p>Languages were first invented by humans, for the benefit of humans.In the annals of computer science, this fact has occasionally beenforgotten.<a href="#FOOTNOTE-2">[2]</a> Since Perl was designed (loosely speaking)by an occasional linguist, it was designed to work smoothly in thesame ways that natural language works smoothly. Naturally, thereare many aspects to this, since natural language works well at manylevels simultaneously. We could enumerate many of these linguisticprinciples here, but the most important principle of language designis that easy things should be easy, and hard things shouldbe possible. (Actually, that's two principles.) They may seemobvious to you, but many computer languages fail at one or the other.</p><blockquote class="footnote"><a name="FOOTNOTE-2"></a><p>[2] More precisely, this fact has occasionally beenremembered.</p></blockquote><p>Natural languages are good at both because people are continually tryingto express both easy things and hard things, so the language evolves tohandle both. Perl was designed first of all to evolve, and indeed ithas evolved. Many people have contributed to the evolution of Perl overthe years. We often joke that a camel is a horse designed by acommittee, but if you think about it, the camel is pretty well adaptedfor life in the desert. The camel has evolved to be relativelyself-sufficient. (On the other hand, the camel has not evolvedto smell good. Neither has Perl.) This is one of the many strangereasons we picked the camel to be Perl's mascot, but it doesn't havemuch to do with linguistics.</p><p>Now when someone utters the word "linguistics", many folks focus in on oneof two things. Either they think of words, or they think of sentences.But words and sentences are just two handy ways to "chunk" speech.Either may be broken down into smaller units of meaning or combinedinto larger units of meaning. And the meaning of any unit dependsheavily on the syntactic, semantic, and pragmatic context in which theunit is located. Natural language has words of various sorts: nouns andverbs and such. If someone says "dog" in isolation, you think of it as a noun,but you can also use the word in other ways. That is, a noun can functionas a verb, an adjective, or an adverb when the context demands it. Ifyou dog a dog during the dog days of summer, you'll be a dog tireddogcatcher.<a href="#FOOTNOTE-3">[3]</a></p><blockquote class="footnote"><a name="FOOTNOTE-3"></a><p>[3] And you're probably dog tired of all thislinguistics claptrap. But we'd like you to understand why Perl isdifferent from the typical computer language, doggone it!</p></blockquote><p>Perl also evaluates words differently in various contexts. We will seehow it does that later. Just remember that Perl is trying to understandwhat you're saying, like any good listener does. Perl works pretty hardto try to keep up its end of the bargain. Just say what you mean, andPerl will usually "get it". (Unless you're talking nonsense, ofcourse--the Perl parser understands Perl a lot better than eitherEnglish or Swahili.)</p><p><a name="INDEX-24"></a>But back to nouns. A noun can name a particular object, or it can namea class of objects generically without specifying which one iscurrently being referred to. Most computer languages make thisdistinction, only we call the particular one a value and the genericone a variable. A value just exists somewhere, who knows where, but avariable gets associated with one or more values over its lifetime. Sowhoever is interpreting the variable has to keep track of thatassociation. That interpreter may be in your brain or in yourcomputer.<a name="INDEX-25"></a><a name="INDEX-26"></a><a name="INDEX-27"></a></p><h3 class="sect2">1.2.1. Variable Syntax</h3><a name="INDEX-28"></a><a name="INDEX-29"></a><a name="INDEX-30"></a><p>A variable is just a handy place to keep something, a place with a name,so you know where to find your special something when you come backlooking for it later. As in real life, there are various kinds ofplaces to store things, some of them rather private, and some of themout in public. Some places are temporary, and other places are morepermanent. Computer scientists love to talk about the "scope" ofvariables, but that's all they mean by it. Perl has various handy waysof dealing with scoping issues, which you'll be happy to learn laterwhen the time is right. Which is not yet. (Look up the adjectives<tt class="literal">local</tt>, <tt class="literal">my</tt>, and <tt class="literal">our</tt> in <a href="ch29_01.htm">Chapter 29, "Functions"</a>, when you get curious, or see"Scoped Declarations" in<a href="ch04_01.htm">Chapter 4, "Statements and Declarations"</a>.)</p><p><a name="INDEX-31"></a><a name="INDEX-32"></a><a name="INDEX-33"></a><a name="INDEX-34"></a><a name="INDEX-35"></a>But a more immediately useful way of classifying variables is by whatsort of data they can hold. As in English, Perl's primary typedistinction is between singular and plural data. Strings and numbersare singular pieces of data, while lists of strings or numbers areplural. (And when we get to object-oriented programming, you'll findthat the typical object looks singular from the outside but plural fromthe inside, like a class of students.) We call a singular variable a<em class="emphasis">scalar</em>, and a plural variable an <em class="emphasis">array</em>. Since a string can bestored in a scalar variable, we might write a slightly longer (andcommented) version of our first example like this:<blockquote><pre class="programlisting">$phrase = "Howdy, world!\n"; # Set a variable.print $phrase; # Print the variable.</pre></blockquote>Note that we did not have to predefine what kind of variable <tt class="literal">$phrase</tt>is. The <tt class="literal">$</tt> character tells Perl that <tt class="literal">phrase</tt> is a scalar variable,that is, one containing a singular value. An array variable, bycontrast, would start with an <tt class="literal">@</tt> character. (It may help you toremember that a <tt class="literal">$</tt> is a stylized "s", for "scalar", while <tt class="literal">@</tt> is astylized "a", for "array".)<a name="INDEX-36"></a><a name="INDEX-37"></a></p><p><a name="INDEX-38"></a><a name="INDEX-39"></a><a name="INDEX-40"></a><a name="INDEX-41"></a>Perl has some other variable types, with unlikely names like "hash","handle", and "typeglob". Like scalars and arrays, these types ofvariables are also preceded by funny characters. For completeness, here are all the funny characters you'll encounter:</p><a name="perl3-tab-funny"></a><table border="1"><tr><th>Type</th><th>Character</th><th>Example</th><th>Is a name for:</th></tr><tr><td>Scalar</td><td><tt class="literal">$</tt></td><td><tt class="literal">$cents</tt></td><td>An individual value (number or string)</td></tr><tr><td>Array</td><td><tt class="literal">@</tt></td><td><tt class="literal">@large</tt></td><td>A list of values, keyed by number</td></tr><tr><td>Hash</td><td><tt class="literal">%</tt></td><td><tt class="literal">%interest</tt></td><td>A group of values, keyed by string<a name="INDEX-42"></a></td></tr><tr><td>Subroutine</td><td><tt class="literal">&</tt></td><td><tt class="literal">&how</tt></td><td>A callable chunk of Perl code<a name="INDEX-43"></a><a name="INDEX-44"></a></td></tr><tr><td>Typeglob</td><td><tt class="literal">*</tt></td><td><tt class="literal">*struck</tt></td><td>Everything named <tt class="literal">struck</tt><a name="INDEX-45"></a><a name="INDEX-46"></a></td></tr></table><p>Some language puristspoint to these funny characters as a reason to abhor Perl. This issuperficial. These characters have many benefits, not least of whichis that variables can be interpolated into strings with no additionalsyntax. Perl scripts are also easy to read (for people who havebothered to learn Perl!) because the nouns stand out from verbs. Andnew verbs can be added to the language without breaking old scripts.(We told you Perl was designed to evolve.) And the noun analogy is notfrivolous--there is ample precedent in English and other languages forrequiring grammatical noun markers. It's how we think! (We think.)</p><h3 class="sect3">1.2.1.1. Singularities</h3><a name="INDEX-47"></a><a name="INDEX-48"></a><p><a name="INDEX-49"></a>From our earlier example, you can see that scalars may be assigned a new valuewith the <tt class="literal">=</tt> operator, just as in many other computer languages. Scalarvariables can be assigned any form of scalar value: integers,floating-point numbers, strings, and even esoteric things likereferences to other variables, or to objects. There are many ways ofgenerating these values for assignment.</p><p><a name="INDEX-50"></a><a name="INDEX-51"></a><a name="INDEX-52"></a><a name="INDEX-53"></a><a name="INDEX-54"></a><a name="INDEX-55"></a><a name="INDEX-56"></a><a name="INDEX-57"></a><a name="INDEX-58"></a>As in the Unix<a href="#FOOTNOTE-4">[4]</a>shell, you can use different quoting mechanisms tomake different kinds of values. Double quotation marks (double quotes)do <em class="emphasis">variable interpolation</em><a href="#FOOTNOTE-5">[5]</a> and<em class="emphasis">backslash interpolation</em> (such as turning<tt class="literal">\n</tt> into a newline) while single quotes suppressinterpolation. And backquotes (the ones leaning tothe left) will execute an external program and return the output of theprogram, so you can capture it as a single string containing all thelines of output.<blockquote><pre class="programlisting">$answer = 42; # an integer$pi = 3.14159265; # a "real" number$avocados = 6.02e23; # scientific notation$pet = "Camel"; # string$sign = "I love my $pet"; # string with interpolation$cost = 'It costs $100'; # string without interpolation$thence = $whence; # another variable's value$salsa = $moles * $avocados; # a gastrochemical expression$exit = system("vi $file"); # numeric status of a command$cwd = `pwd`; # string output from a command</pre></blockquote><a name="INDEX-59"></a><a name="INDEX-60"></a><a name="INDEX-61"></a><a name="INDEX-62"></a>And while we haven't covered fancy values yet, we should point out thatscalars may also hold references to other data structures, includingsubroutines and objects.<blockquote><pre class="programlisting">$ary = \@myarray; # reference to a named array$hsh = \%myhash; # reference to a named hash$sub = \&mysub; # reference to a named subroutine$ary = [1,2,3,4,5]; # reference to an unnamed array$hsh = {Na => 19, Cl => 35}; # reference to an unnamed hash$sub = sub { print $state }; # reference to an unnamed subroutine$fido = new Camel "Amelia"; # reference to an object</pre></blockquote><a name="INDEX-63"></a></p><blockquote class="footnote"><a name="FOOTNOTE-4"></a><p>[4]Here and elsewhere, when we say Unix, we meanany operating system resembling Unix, including BSD, Linux, and, of course,Unix.</p></blockquote><blockquote class="footnote"><a name="FOOTNOTE-5"></a><p>[5]Sometimescalled "substitution" byshell programmers, but we prefer to reserve that word for somethingelse in Perl. So please call it interpolation. We're using the termin the textual sense ("this passage is a Gnostic interpolation") ratherthan in the mathematical sense ("this point on the graph is aninterpolation between two other points").</p></blockquote><p><a name="INDEX-64"></a><a name="INDEX-65"></a><a name="INDEX-66"></a><a name="INDEX-67"></a><a name="INDEX-68"></a><a name="INDEX-69"></a><a name="INDEX-70"></a>If you use a variable that has never been assigned a value, the
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -