📄 ch15_02.htm
字号:
<html><head><title>Manipulating a Substring with substr (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="ch15_01.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="ch15_03.htm"><img alt="Next" border="0" src="../gifs/txtnexta.gif" /></a></td></tr></table></div><h2 class="sect1">15.2. Manipulating a Substring with substr</h2><p>The <tt class="literal">substr</tt><a name="INDEX-1004" /> operator works with only a part of alarger string. It looks like this:</p><blockquote><pre class="code">$part = substr($string, $initial_position, $length);</pre></blockquote><p>It takes three arguments: a string value, a zero-based initialposition (like the return value of <tt class="literal">index</tt>), and alength for the substring. The return value is the substring:</p><blockquote><pre class="code">my $mineral = substr("Fred J. Flintstone", 8, 5); # gets "Flint"my $rock = substr "Fred J. Flintstone", 13, 1000; # gets "stone"</pre></blockquote><p>As you may have noticed in the previous example, if the requestedlength (<tt class="literal">1000</tt> characters, in this case) would gopast the end of the string, there's no complaint from Perl, butyou simply get a shorter string than you might have. But if you wantto be sure to go to the end of the string, however long or short itmay be, just omit that third parameter (the length), like this:</p><blockquote><pre class="code">my $pebble = substr "Fred J. Flintstone", 13; # gets "stone"</pre></blockquote><p>The initial position of the substring in the larger string can benegative, counting from the end of the string (that is, position<tt class="literal">-1</tt> is the last character).<a href="#FOOTNOTE-334">[334]</a> In this example, position<tt class="literal">-3</tt> is three characters from the end of the string,which is the location of the letter <tt class="literal">i</tt>:</p><blockquote class="footnote"> <a name="FOOTNOTE-334" /><p>[334]This isanalogous to what we saw with array indices in <a href="ch03_01.htm">Chapter 3, "Lists and Arrays "</a>. Just as arrays may be indexed either from<tt class="literal">0</tt> (the first element) upwards or from <tt class="literal">-1</tt>(the last element) downwards, substring locations may beindexed from position <tt class="literal">0</tt> (at the first character)upwards or from position <tt class="literal">-1</tt> (at the lastcharacter) downwards.</p> </blockquote><blockquote><pre class="code">my $out = substr("some very long string", -3, 2); # $out gets "in"</pre></blockquote><p>As you might expect,<tt class="literal">index</tt><a name="INDEX-1005" /> and <tt class="literal">substr</tt> workwell together. In this example, we can extract a substring thatstarts at the location of the letter <tt class="literal">l</tt>:</p><blockquote><pre class="code">my $long = "some very very long string";my $right = substr($long, index($long, "l") );</pre></blockquote><p>Now here's something really cool: The selected portion of thestring can be changed if the string is a variable:<a href="#FOOTNOTE-335">[335]</a></p><blockquote class="footnote"><a name="FOOTNOTE-335" /><p>[335]Well, technically, it can be any <em class="firstterm">lvalue</em>.What that term means precisely is beyond the scope of this book, butyou can think of it as anything that can be put on the left side ofthe equals sign (<tt class="literal">=</tt>) in a scalar assignment.That's usually a variable, but it can (as you see here) even bean invocation of the <tt class="literal">substr </tt>operator. </p></blockquote><blockquote><pre class="code">my $string = "Hello, world!";substr($string, 0, 5) = "Goodbye"; # $string is now "Goodbye, world!"</pre></blockquote><p>As you see, the assigned (sub)string doesn't have to be thesame length as the substring it's replacing. The string'slength is adjusted to fit. Or if that wasn't cool enough toimpress you, you could use the binding operator(<tt class="literal">=~</tt>) to restrict an operation to work with justpart of a string. This example replaces <tt class="literal">fred</tt> with<tt class="literal">barney</tt> wherever possible within just the lasttwenty characters of a string:</p><blockquote><pre class="code">substr($string, -20) =~ s/fred/barney/g;</pre></blockquote><p>To be completely honest, we've never actually needed thatfunctionality in any of our own code, and chances are thatyou'll never need it either. But it's nice to know thatPerl can do more than you'll ever need, isn't it?</p><p>Much of the work that <tt class="literal">substr</tt> and<tt class="literal">index</tt> do could be done with regular expressions.Use those where they're appropriate. But<tt class="literal">substr</tt> and <tt class="literal">index</tt> can often befaster, since they don't have the overhead of the regularexpression engine: they're never case-insensitive, they have nometacharacters to worry about, and they don't set any of thememory variables.</p><p>Besides assigning to the <tt class="literal">substr</tt> function (whichlooks a little weird at first glance, perhaps), you can also use<tt class="literal">substr</tt> in a slightly more traditionalmanner<a href="#FOOTNOTE-336">[336]</a> with the four-argument version, in which the fourthargument is the replacement substring:</p><blockquote class="footnote"> <a name="FOOTNOTE-336" /><p>[336]By traditional we mean in the "functioninvocation" sense, but not the "Perl" sense, sincethis feature was introduced to Perl relatively recently.</p></blockquote><blockquote><pre class="code">my $previous_value = substr($string, 0, 5, "Goodbye");</pre></blockquote><p>The previous value comes back as the return value, although asalways, you can use this function in a void context to simply discardit.<a name="INDEX-1006" /></p><hr width="684" align="left" /><div class="navbar"><table width="684" border="0"><tr><td align="left" valign="top" width="228"><a href="ch15_01.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="ch15_03.htm"><img alt="Next" border="0" src="../gifs/txtnexta.gif" /></a></td></tr><tr><td align="left" valign="top" width="228">15. Strings and Sorting</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">15.3. Formatting Data with sprintf</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 + -