📄 ch01_09.htm
字号:
<HTML><HEAD><TITLE>Recipe 1.8. Expanding Variables in User Input (Perl Cookbook)</TITLE><METANAME="DC.title"CONTENT="Perl Cookbook"><METANAME="DC.creator"CONTENT="Tom Christiansen & Nathan Torkington"><METANAME="DC.publisher"CONTENT="O'Reilly & Associates, Inc."><METANAME="DC.date"CONTENT="1999-07-02T01:29:03Z"><METANAME="DC.type"CONTENT="Text.Monograph"><METANAME="DC.format"CONTENT="text/html"SCHEME="MIME"><METANAME="DC.source"CONTENT="1-56592-243-3"SCHEME="ISBN"><METANAME="DC.language"CONTENT="en-US"><METANAME="generator"CONTENT="Jade 1.1/O'Reilly DocBook 3.0 to HTML 4.0"><LINKREV="made"HREF="mailto:online-books@oreilly.com"TITLE="Online Books Comments"><LINKREL="up"HREF="ch01_01.htm"TITLE="1. Strings"><LINKREL="prev"HREF="ch01_08.htm"TITLE="1.7. Expanding and Compressing Tabs"><LINKREL="next"HREF="ch01_10.htm"TITLE="1.9. Controlling Case"></HEAD><BODYBGCOLOR="#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="Perl Cookbook"><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><p><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch01_08.htm"TITLE="1.7. Expanding and Compressing Tabs"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 1.7. Expanding and Compressing Tabs"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1"><ACLASS="chapter"REL="up"HREF="ch01_01.htm"TITLE="1. Strings"></A></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch01_10.htm"TITLE="1.9. Controlling Case"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 1.9. Controlling Case"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch01-chap01_expanding_1">1.8. Expanding Variables in User Input</A></H2><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch01-pgfId-813">Problem <ACLASS="indexterm"NAME="ch01-idx-1000010249-0"></A><ACLASS="indexterm"NAME="ch01-idx-1000010249-1"></A><ACLASS="indexterm"NAME="ch01-idx-1000010249-2"></A><ACLASS="indexterm"NAME="ch01-idx-1000010249-3"></A></A></H3><PCLASS="para">You've read in a string with an embedded variable reference, such as:</P><PRECLASS="programlisting">You owe $debt to me.</PRE><PCLASS="para">Now you want to replace <CODECLASS="literal">$debt</CODE> in the string with its value.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch01-pgfId-823">Solution</A></H3><PCLASS="para">Use a substitution with <ACLASS="indexterm"NAME="ch01-idx-1000011573-0"></A>symbolic references if the variables are all globals:</P><PRECLASS="programlisting">$text =~ s/\$(\w+)/${$1}/g;</PRE><PCLASS="para">But use a double <CODECLASS="literal">/ee</CODE><ACLASS="indexterm"NAME="ch01-idx-1000010696-0"></A> if they might be lexical (<CODECLASS="literal">my</CODE>) variables:</P><PRECLASS="programlisting">$text =~ s/(\$\w+)/$1/gee;</PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch01-pgfId-835">Discussion</A></H3><PCLASS="para">The first technique is basically "find what looks like a variable name, and then use symbolic dereferencing to interpolate its contents." If <CODECLASS="literal">$1</CODE> contains the string <CODECLASS="literal">somevar</CODE>, then <CODECLASS="literal">${$1}</CODE> will be whatever <CODECLASS="literal">$somevar</CODE> contains. This won't work if the <CODECLASS="literal">use</CODE> <CODECLASS="literal">strict</CODE> <CODECLASS="literal">'refs'</CODE> pragma is in effect because that bans symbolic dereferencing.</P><PCLASS="para">Here's an example:</P><PRECLASS="programlisting">use vars qw($rows $cols);no strict 'refs'; # for ${$1}/g belowmy $text;($rows, $cols) = (24, 80);$text = q(I am $rows high and $cols long); # like single quotes!$text =~ s/\$(\w+)/${$1}/g;print $text;<CODECLASS="userinput"><B><CODECLASS="replaceable"><I>I am 24 high and 80 long</I></CODE></B></CODE></PRE><PCLASS="para">You may have seen the <CODECLASS="literal">/e</CODE><ACLASS="indexterm"NAME="ch01-idx-1000010255-0"></A> substitution modifier used to evaluate the replacement as code rather than as a string. It's designed for situations such as doubling every whole number in a string:</P><PRECLASS="programlisting">$text = "I am 17 years old";$text =~ s/(\d+)/2 * $1/eg; </PRE><PCLASS="para">When Perl is compiling your program and sees a <CODECLASS="literal">/e</CODE> on a substitute, it compiles the code in the replacement block along with the rest of your program, long before the substitution actually happens. When a substitution is made, <CODECLASS="literal">$1</CODE> is replaced with the string that matched. The code to evaluate would then be something like:</P><PRECLASS="programlisting">2 * 17</PRE><PCLASS="para">If we tried saying:</P><PRECLASS="programlisting">$text = 'I am $AGE years old'; # note single quotes$text =~ s/(\$\w+)/$1/eg; # WRONG</PRE><PCLASS="para">assuming <CODECLASS="literal">$text</CODE> held a mention of the variable <CODECLASS="literal">$AGE</CODE>, Perl would dutifully replace <CODECLASS="literal">$1</CODE> with <CODECLASS="literal">$AGE</CODE> and then evaluate code that looked like:</P><PRECLASS="programlisting">'$AGE'</PRE><PCLASS="para">which just yields us our original string back again. We need to evaluate the result <EMCLASS="emphasis">again</EM> to get the value of the variable. To do that, just add another <CODECLASS="literal">/e</CODE>:</P><PRECLASS="programlisting">$text =~ s/(\$\w+)/$1/eeg; # finds my() variables</PRE><PCLASS="para">Yes, you can have as many <CODECLASS="literal">/e</CODE> modifiers as you'd like. Only the first one is compiled and syntax-checked with the rest of your program. This makes it work like the <CODECLASS="literal">eval</CODE><ACLASS="indexterm"NAME="ch01-idx-1000011509-0"></A> <CODECLASS="literal">{BLOCK}</CODE> construct, except that it doesn't trap exceptions. Think of it more as a <CODECLASS="literal">do</CODE> <CODECLASS="literal">{BLOCK}</CODE> instead.</P><PCLASS="para">Subsequent <CODECLASS="literal">/e</CODE> modifiers are quite different. They're more like the <CODECLASS="literal">eval</CODE> "<CODECLASS="literal">STRING</CODE>" construct. They don't get compiled until run-time. A small advantage of this scheme is that it doesn't make you put a <CODECLASS="literal">no</CODE> <CODECLASS="literal">strict</CODE> <CODECLASS="literal">'refs'</CODE> pragma in the block. A tremendous advantage is that unlike the symbolic dereferencing, this mechanism can actually find lexical variables created with <CODECLASS="literal">my</CODE>, something symbolic references can never do.</P><PCLASS="para">The following example uses the <CODECLASS="literal">/x</CODE><ACLASS="indexterm"NAME="ch01-idx-1000010256-0"></A> modifier to enable whitespace and comments in the pattern part of the substitute and <CODECLASS="literal">/e</CODE> to evaluate the right-hand side as code. The <CODECLASS="literal">/e</CODE> modifier gives you more control over what happens in case of error or other extenuating circumstances, as we have here:</P><PRECLASS="programlisting"># expand variables in $text, but put an error message in# if the variable isn't defined$text =~ s{ \$ # find a literal dollar sign (\w+) # find a "word" and store it in $1}{ no strict 'refs'; # for $$1 below if (defined $$1) { $$1; # expand global variables only } else { "[NO VARIABLE: \$$1]"; # error msg }}egx;</PRE><PCLASS="para">Note that the syntax of <CODECLASS="literal">$$1</CODE> has changed for Perl 5.004: it used to mean <CODECLASS="literal">${$}1</CODE> but now means <CODECLASS="literal">${$1}</CODE>. For backwards compatibility, in strings it still takes the old meaning (but generates a warning with <BCLASS="emphasis.bold">-w</B>). People will write <CODECLASS="literal">${$1}</CODE> within a string to keep from dereferencing the PID variable. If <CODECLASS="literal">$$</CODE> were 23448, then <CODECLASS="literal">$$1</CODE> in a string would turn into <CODECLASS="literal">234481</CODE>, not the contents of the variable whose name was stored in <CODECLASS="literal">$1</CODE>. <ACLASS="indexterm"NAME="ch01-idx-1000011574-0"></A></P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch01-pgfId-919">See Also</A></H3><PCLASS="para">The <CODECLASS="literal">s///</CODE> operator in <EMCLASS="emphasis">perlre </EM>(1) and <EMCLASS="emphasis">perlop </EM>(1) and the <ACLASS="olink"HREF="../prog/ch02_04.htm">"Pattern Matching"</A> and <ACLASS="olink"HREF="../prog/ch02_04.htm#PERL2-CH-2-SECT-4.1">"Regular Expressions"</A> sections of <ACLASS="olink"HREF="../prog/ch02_01.htm">Chapter 2</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A>; the <CODECLASS="literal">eval</CODE> function in <EMCLASS="emphasis">perlfunc </EM>(1) and <ACLASS="olink"HREF="../prog/ch03_01.htm">Chapter 3</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A>; the similar use of substitutions in <ACLASS="xref"HREF="ch20_10.htm"TITLE="Creating HTML Templates">Recipe 20.9</A>. <ACLASS="indexterm"NAME="ch01-idx-1000010251-0"></A><ACLASS="indexterm"NAME="ch01-idx-1000010251-1"></A><ACLASS="indexterm"NAME="ch01-idx-1000010251-2"></A><ACLASS="indexterm"NAME="ch01-idx-1000010251-3"></A></P></DIV></DIV><DIVCLASS="htmlnav"><P></P><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch01_08.htm"TITLE="1.7. Expanding and Compressing Tabs"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 1.7. Expanding and Compressing Tabs"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="book"HREF="index.htm"TITLE="Perl Cookbook"><IMGSRC="../gifs/txthome.gif"ALT="Perl Cookbook"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch01_10.htm"TITLE="1.9. Controlling Case"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 1.9. Controlling Case"BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">1.7. Expanding and Compressing Tabs</TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="index"HREF="index/index.htm"TITLE="Book Index"><IMGSRC="../gifs/index.gif"ALT="Book Index"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228">1.9. Controlling Case</TD></TR></TABLE><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><FONTSIZE="-1"></DIV<!-- LIBRARY NAV BAR --> <img src="../gifs/smnavbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links"><p> <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 + -