📄 ch06_21.htm
字号:
<HTML><HEAD><TITLE>Recipe 6.20. Matching Abbreviations (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:35:06Z"><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="ch06_01.htm"TITLE="6. Pattern Matching"><LINKREL="prev"HREF="ch06_20.htm"TITLE="6.19. Matching a Valid Mail Address"><LINKREL="next"HREF="ch06_22.htm"TITLE="6.21. Program: urlify"></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="ch06_20.htm"TITLE="6.19. Matching a Valid Mail Address"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 6.19. Matching a Valid Mail Address"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1"><ACLASS="chapter"REL="up"HREF="ch06_01.htm"TITLE="6. Pattern Matching"></A></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch06_22.htm"TITLE="6.21. Program: urlify"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 6.21. Program: urlify"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch06-chap06_matching_7">6.20. Matching Abbreviations</A></H2><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch06-pgfId-2423">Problem<ACLASS="indexterm"NAME="ch06-idx-1000007723-0"></A><ACLASS="indexterm"NAME="ch06-idx-1000007723-1"></A><ACLASS="indexterm"NAME="ch06-idx-1000007723-2"></A></A></H3><PCLASS="para">Suppose you had a list of commands, such as <CODECLASS="literal">"send"</CODE>, <CODECLASS="literal">"abort"</CODE>, <CODECLASS="literal">"list"</CODE>, and <CODECLASS="literal">"edit"</CODE>. The user types one in, but you don't want to make them type out the whole thing.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch06-pgfId-2429">Solution</A></H3><PCLASS="para">You can use the following technique if the strings all start with different characters or if you want to arrange the matches so one takes precedence over another, as <CODECLASS="literal">"SEND"</CODE> has precedence over <CODECLASS="literal">"STOP"</CODE> here:</P><PRECLASS="programlisting">chomp($answer = <>);if ("SEND" =~ /^\Q$answer/i) { print "Action is send\n" }elsif ("STOP" =~ /^\Q$answer/i) { print "Action is stop\n" }elsif ("ABORT" =~ /^\Q$answer/i) { print "Action is abort\n" }elsif ("LIST" =~ /^\Q$answer/i) { print "Action is list\n" }elsif ("EDIT" =~ /^\Q$answer/i) { print "Action is edit\n" }</PRE><PCLASS="para">Or you can use the Text::Abbrev module:</P><PRECLASS="programlisting">use Text::Abbrev;$href = abbrev qw(send abort list edit);for (print "Action: "; <>; print "Action: ") { chomp; my $action = $href->{ lc($_) }; print "Action is $action\n";}</PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch06-pgfId-2463">Discussion</A></H3><PCLASS="para">The first technique switches the typical order of a match. Normally you have a variable on the left side of the match and a known pattern on the right side. We might try to decide which action the user wanted us to take by saying <CODECLASS="literal">$answer</CODE> <CODECLASS="literal">=~</CODE> <CODECLASS="literal">/^ABORT/i</CODE>, which is true if <CODECLASS="literal">$answer</CODE> begins with the string <CODECLASS="literal">"ABORT"</CODE>. It matches whether <CODECLASS="literal">$answer</CODE> has anything after <CODECLASS="literal">"ABORT"</CODE>, so <CODECLASS="literal">"ABORT</CODE> <CODECLASS="literal">LATER"</CODE> would still match. Handling abbreviations generally requires quite a bit of ugliness: <CODECLASS="literal">$answer</CODE> <CODECLASS="literal">=~</CODE> <CODECLASS="literal">/^A(B(O(R(T)?)?)?)?$/i</CODE>.</P><PCLASS="para">Compare the classic <CODECLASS="literal">"variable</CODE> <CODECLASS="literal">=~</CODE> <CODECLASS="literal">pattern"</CODE> with <CODECLASS="literal">"ABORT"</CODE> <CODECLASS="literal">=~</CODE> <CODECLASS="literal">/^\Q$answer/i</CODE>. The <CODECLASS="literal">\Q</CODE> escapes any characters that would otherwise be treated as regular expression, so your program won't blow up if the user enters an invalid pattern. When the user enters something like <CODECLASS="literal">"ab"</CODE>, the expanded match becomes <CODECLASS="literal">"ABORT"</CODE> <CODECLASS="literal">=~</CODE> <CODECLASS="literal">/^ab/i</CODE> after variable substitution and metaquoting. This matches.</P><PCLASS="para">The standard Text::Abbrev module takes a different approach. You give it a list of words, and it returns a reference to a hash whose keys are all unambiguous abbreviations and whose values are the fully expanded strings. So if <CODECLASS="literal">$href</CODE> were created as in the Solution example, <CODECLASS="literal">$href->{$var}</CODE> would return the string <CODECLASS="literal">"abort"</CODE>.</P><PCLASS="para">This technique is commonly used to call a function based on the name of the string the user types in. Do this by using a symbolic reference, like:</P><PRECLASS="programlisting">$name = 'send';&$name();</PRE><PCLASS="para">But that's scary, because it allows the user to run any function in our program, assuming they know its name. It also runs afoul of that pesky <CODECLASS="literal">use</CODE> <CODECLASS="literal">strict</CODE> <CODECLASS="literal">'refs'</CODE> pragma.</P><PCLASS="para">Here's a partial program that creates a hash in which the key is the command name and the value is a reference to the function to call for that command:</P><PRECLASS="programlisting"># assumes that &invoke_editor, &deliver_message,# $file and $PAGER are defined somewhere else.use Text::Abbrev;my($href, %actions, $errors);%actions = ( "edit" => \&invoke_editor, "send" => \&deliver_message, "list" => sub { system($PAGER, $file) }, "abort" => sub { print "See ya!\n"; exit; }, "" => sub { print "Unknown command: $cmd\n"; $errors++; },);$href = abbrev(keys %actions);local $_;for (print "Action: "; <>; print "Action: ") { s/^\s+//; # trim leading white space s/\s+$//; # trim trailing white space next unless $_; $actions->{ $href->{ lc($_) } }->();}</PRE><PCLASS="para">The last statement could have been written like this if you're not into tight expressions or need practice typing:</P><PRECLASS="programlisting">$abbreviation = lc($_);$expansion = $href->{$abbreviation};$coderef = $actions->{$expansion};&$coderef();<ACLASS="indexterm"NAME="ch06-idx-1000007725-0"></A><ACLASS="indexterm"NAME="ch06-idx-1000007725-1"></A><ACLASS="indexterm"NAME="ch06-idx-1000007725-2"></A></PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch06-pgfId-2547">See Also</A></H3><PCLASS="para">The documentation for the standard Text::Abbrev module (also in <ACLASS="olink"HREF="../prog/ch07_01.htm">Chapter 7</A> of <CITECLASS="citetitle">Programming Perl </CITE>); interpolation is explained in the "Scalar Value Constructors" section of <ICLASS="filename">perldata </I>(1), and in the <ACLASS="olink"HREF="../prog/ch02_03.htm#PERL2-CH-2-SECT-3.2.2">"String literals"</A> section 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></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="ch06_20.htm"TITLE="6.19. Matching a Valid Mail Address"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 6.19. Matching a Valid Mail Address"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="ch06_22.htm"TITLE="6.21. Program: urlify"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 6.21. Program: urlify"BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">6.19. Matching a Valid Mail Address</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">6.21. Program: urlify</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 + -