📄 ch02_05.htm
字号:
<html><head><title>Names (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="Names"><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_04.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_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">2.5. Names</h2><p><a name="INDEX-459"></a><a name="INDEX-460"></a><a name="INDEX-461"></a><a name="INDEX-462"></a><a name="INDEX-463"></a><a name="INDEX-464"></a><a name="INDEX-465"></a><a name="INDEX-466"></a><a name="INDEX-467"></a><a name="INDEX-468"></a>We've talked about storing values in variables, but the variablesthemselves (their names and their associated definitions) also need tobe stored somewhere. In the abstract, these places are known as<em class="emphasis">namespaces</em>. Perl provides two kinds of namespaces, which are oftencalled <em class="emphasis">symbol tables</em> and <em class="emphasis">lexical scopes</em>.<a href="#FOOTNOTE-6">[6]</a> Youmay have an arbitrary number of symbol tables or lexical scopes, butevery name you define gets stored in one or the other. We'll explainboth kinds of namespaces as we go along. For now we'll just say thatsymbol tables are global hashes that happen to contain symbol tableentries for global variables (including the hashes for other symboltables). In contrast, lexical scopes are <em class="emphasis">unnamed</em>scratchpads thatdon't live in any symbol table, but are attached to a block of code inyour program. They contain variables that can only be seen by theblock. (That's what we mean by a <em class="emphasis">scope</em>). The <em class="emphasis">lexical</em> part justmeans, "having to do with text", which is not at all what alexicographer would mean by it. Don't blame us.)</p><blockquote class="footnote"><a name="FOOTNOTE-6"></a><p>[6] We also callthem <em class="emphasis">packages</em> and <em class="emphasis">pads</em> when we're talking about Perl's specificimplementations, but those longer monikers are the generic industryterms, so we're pretty much stuck with them. Sorry.</p></blockquote><p><a name="INDEX-469"></a>Within any given namespace (whether global or lexical), every variabletype has its own subnamespace, determined by the funny character. Youcan, without fear of conflict, use the same name for a scalar variable,an array, or a hash (or, for that matter, a filehandle, a subroutinename, a label, or your pet llama). This means that <tt class="literal">$foo</tt> and <tt class="literal">@foo</tt>are two different variables. Together with the previous rules, it alsomeans that <tt class="literal">$foo[1]</tt> is an element of <tt class="literal">@foo</tt> totally unrelated to thescalar variable <tt class="literal">$foo</tt>. This may seem a bit weird, but that's okay,because it <em class="emphasis">is</em> weird.</p><p><a name="INDEX-470"></a><a name="INDEX-471"></a>Subroutines may be named with an initial <tt class="literal">&</tt>, although the funnycharacter is optional when calling the subroutine. Subroutines aren'tgenerally considered lvalues, though recent versions of Perl allow youto return an lvalue from a subroutine and assign to that, so it canlook as though you're assigning to the subroutine.</p><p><a name="INDEX-472"></a>Sometimes you just want a name for "everything named foo" regardless ofits funny character. So symbol table entries can be named with aninitial <tt class="literal">*</tt>, where the asterisk stands for all the other funnycharacters. These are called <em class="emphasis">typeglobs</em>, and they have several uses.They can also function as lvalues. Assignment to <em class="emphasis">typeglobs</em>is how Perl implements importing of symbols from one symbol table toanother. More about that later too.<a name="INDEX-473"></a></p><p><a name="INDEX-474"></a><a name="INDEX-475"></a><a name="INDEX-476"></a><a name="INDEX-477"></a><a name="INDEX-478"></a><a name="INDEX-479"></a>Like most computer languages, Perl has a list of reserved words that itrecognizes as special keywords. However, because variable names alwaysstart with a funny character, reserved words don't actually conflictwith variable names. Certain other kinds of names don't have funnycharacters, though, such as labels and filehandles. With these, you dohave to worry (a little) about conflicting with reserved words. Sincemost reserved words are entirely lowercase, we recommend that you picklabel and filehandle names that contain uppercase letters. Forexample, if you say <tt class="literal">open(LOG, logfile)</tt> rather than theregrettable <tt class="literal">open(log, "logfile")</tt>, you won't confusePerl into thinking you're talking about the built-in <tt class="literal">log</tt>operator (which does logarithms, not tree trunks). Using uppercasefilehandles also improves readability<a href="#FOOTNOTE-7">[7]</a>and protects you from conflict with reservedwords we might add in the future. For similar reasons, user-definedmodules are typically named with initial capitals so that they'll lookdifferent from the built-in modules known as pragmas, which are namedin all lowercase. And when we get to object-oriented programming,you'll notice that class names are usually capitalized for the samereason.<a name="INDEX-480"></a><a name="INDEX-481"></a></p><blockquote class="footnote"><a name="FOOTNOTE-7"></a><p>[7] One of thedesign principles of Perl is that different things should lookdifferent. Contrast this with languages that try to force differentthings to look the same, to the detriment of readability.</p></blockquote><p><a name="INDEX-482"></a><a name="INDEX-483"></a><a name="INDEX-484"></a><a name="INDEX-485"></a><a name="INDEX-486"></a>As you might deduce from the preceding paragraph, case is significantin identifiers--<tt class="literal">FOO</tt>, <tt class="literal">Foo</tt>, and <tt class="literal">foo</tt> are all different names inPerl. Identifiers start with a letter or underscore and may be of anylength (for values of "any" ranging between 1 and 251, inclusive) andmay contain letters, digits, and underscores. This includes Unicodeletters and digits. Unicode ideographs also count as letters, but wedon't recommend you use them unless you can read them. See<a href="ch15_01.htm">Chapter 15, "Unicode"</a>.</p><p>Names that follow funny characters don't have to be identifiers, strictlyspeaking. Theycan start with a digit, in which case they may only contain moredigits, as in <tt class="literal">$123</tt>. Names that start with anything other than aletter, digit, or underscore are (usually) limited to that onecharacter (like <tt class="literal">$?</tt> or <tt class="literal">$$</tt>), and generally have a predefinedsignificance to Perl. For example, just as in the Bourne shell, <tt class="literal">$$</tt>is the current process ID and <tt class="literal">$?</tt> the exit status of your last childprocess.<a name="INDEX-487"></a><a name="INDEX-488"></a></p><p><a name="INDEX-489"></a><a name="INDEX-490"></a>As of version 5.6, Perl also has an extensible syntax for internalvariables names. Any variable of the form<tt class="literal">${^</tt><em class="replaceable">NAME</em><tt class="literal">}</tt>is a special variable reserved for use by Perl. All thesenon-identifier names are forced to be in the main symbol table. See<a href="ch28_01.htm">Chapter 28, "Special Names"</a>, for some examples.</p><p><a name="INDEX-491"></a><a name="INDEX-492"></a><a name="INDEX-493"></a><a name="INDEX-494"></a><a name="INDEX-495"></a>It's tempting to think of identifiers and names as the same thing,but when we say <em class="emphasis">name</em>, we usually mean a fully qualified name,that is, a name that says which symbol table it lives in. Suchnames may be formed of a sequence of identifiers separated by the <tt class="literal">::</tt>token:<blockquote><pre class="programlisting">$Santa::Helper::Reindeer::Rudolph::nose</pre></blockquote>That works just like the directories and filenames in a pathname:<blockquote><pre class="programlisting">/Santa/Helper/Reindeer/Rudolph/nose</pre></blockquote>In the Perl version of that notion, all the leading identifiers are thenames of nested symbol tables, and the last identifier is the name ofthe variable within the most deeply nested symbol table. Forinstance, in the variable above, the symbol table is named<tt class="literal">Santa::Helper::Reindeer::Rudolph::</tt>, and the actualvariable within that symbol table is <tt class="literal">$nose</tt>. (Thevalue of that variable is, of course, "<tt class="literal">red</tt>".)<a name="INDEX-496"></a></p><p><a name="INDEX-497"></a><a name="INDEX-498"></a><a name="INDEX-499"></a><a name="INDEX-500"></a> A symbol table inPerl is also known as a <em class="emphasis">package</em>, so these areoften called package variables. Package variables are nominallyprivate to the package in which they exist, but are global in thesense that the packages themselves are global. That is, anyone canname the package to get at the variable; it's just hard to do this byaccident. For instance, any program that mentions<tt class="literal">$Dog::bert</tt> is asking for the<tt class="literal">$bert</tt> variable within the <tt class="literal">Dog::</tt>package. That is an entirely separate variable from
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -