⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch15_02.htm

📁 By Tom Christiansen and Nathan Torkington ISBN 1-56592-243-3 First Edition, published August 1998
💻 HTM
📖 第 1 页 / 共 2 页
字号:
<HTML><HEAD><TITLE>Recipe 15.1. Parsing Program Arguments (Perl Cookbook)</TITLE><METANAME="DC.title"CONTENT="Perl Cookbook"><METANAME="DC.creator"CONTENT="Tom Christiansen &amp; Nathan Torkington"><METANAME="DC.publisher"CONTENT="O'Reilly &amp; Associates, Inc."><METANAME="DC.date"CONTENT="1999-07-02T01:43:14Z"><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="ch15_01.htm"TITLE="15. User Interfaces"><LINKREL="prev"HREF="ch15_01.htm"TITLE="15.0. Introduction"><LINKREL="next"HREF="ch15_03.htm"TITLE="15.2. Testing Whether a Program Is Running Interactively"></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="ch15_01.htm"TITLE="15.0. Introduction"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 15.0. Introduction"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1"><ACLASS="chapter"REL="up"HREF="ch15_01.htm"TITLE="15. User Interfaces"></A></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch15_03.htm"TITLE="15.2. Testing Whether a Program Is Running Interactively"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 15.2. Testing Whether a Program Is Running Interactively"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch15-34446">15.1. Parsing Program Arguments</A></H2><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch15-pgfId-83">Problem<ACLASS="indexterm"NAME="ch15-idx-1000005023-0"></A><ACLASS="indexterm"NAME="ch15-idx-1000005023-1"></A><ACLASS="indexterm"NAME="ch15-idx-1000005023-2"></A><ACLASS="indexterm"NAME="ch15-idx-1000005023-3"></A><ACLASS="indexterm"NAME="ch15-idx-1000005023-4"></A><ACLASS="indexterm"NAME="ch15-idx-1000005023-5"></A></A></H3><PCLASS="para">You want to let users change your program's behavior by giving options on the command line. For instance, you want to allow the user to control the level of output that your program produces with a <BCLASS="emphasis.bold">-v</B> (verbose) option.<ACLASS="indexterm"NAME="ch15-idx-1000005062-0"></A></P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch15-pgfId-89">Solution</A></H3><PCLASS="para">Use the standard Getopt::Std module to permit single-character options:</P><PRECLASS="programlisting">use Getopt::Std;# -v ARG, -D ARG, -o ARG, sets $opt_v, $opt_D, $opt_ogetopt(&quot;vDo&quot;);              # -v ARG, -D ARG, -o ARG, sets $args{v}, $args{D}, $args{o}getopt(&quot;vDo&quot;, \%args);getopts(&quot;vDo:&quot;);         # -v, -D, -o ARG, sets $opt_v, $opt_D, $opt_ogetopts(&quot;vDo:&quot;, \%args); # -v, -D, -o ARG, sets $args{v}, $args{D}, $args{o}</PRE><PCLASS="para">Or, use the standard <ACLASS="indexterm"NAME="ch15-idx-1000005033-0"></A>Getopt::Long module to permit named arguments:</P><PRECLASS="programlisting">use Getopt::Long;GetOptions( &quot;verbose&quot;  =&gt; \$verbose,     # --verbose            &quot;Debug&quot;    =&gt; \$debug,       # --Debug            &quot;output=s&quot; =&gt; \$output );    # --output=string or --output=string</PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch15-pgfId-119">Discussion</A></H3><PCLASS="para">Most traditional programs like <EMCLASS="emphasis">ls</EM> and <EMCLASS="emphasis">rm</EM> take single-character options (also known as flags or switches), such as <BCLASS="emphasis.bold">-l</B> and <BCLASS="emphasis.bold">-r</B>. In the case of <EMCLASS="emphasis">ls -l</EM> and <EMCLASS="emphasis">rm -r</EM>, the argument is Boolean: either it is present or it isn't. Contrast this with <EMCLASS="emphasis">gcc -o compiledfile source.c</EM>, where <EMCLASS="emphasis">compiledfile</EM> is a value associated with the option <BCLASS="emphasis.bold">-o</B>. We can combine Boolean options into a single option in any order. For example:</P><PRECLASS="programlisting">% rm -r -f /tmp/testdir</PRE><PCLASS="para">Another way of saying this is:</P><PRECLASS="programlisting">% rm -rf /tmp/testdir</PRE><PCLASS="para">The Getopt::Std module, part of the standard Perl distribution, parses these types of traditional options. Its <CODECLASS="literal">getopt</CODE><ACLASS="indexterm"NAME="ch15-idx-1000005035-0"></A> function takes a single string of characters, each corresponding to an option that takes a value, parses the command-line arguments stored in <CODECLASS="literal">@ARGV</CODE>, and sets a global variable for each option. For example, the value for the <BCLASS="emphasis.bold">-D</B> option will be stored in <CODECLASS="literal">$opt_D</CODE>. All options parsed though <CODECLASS="literal">getopt</CODE> are value options, not Boolean options.</P><PCLASS="para">Getopt::Std also provides the <CODECLASS="literal">getopts</CODE><ACLASS="indexterm"NAME="ch15-idx-1000005034-0"></A> function, which lets you specify whether each option is Boolean or takes a value. Arguments that take a value, like the <BCLASS="emphasis.bold">-o</B> option to <EMCLASS="emphasis">gcc</EM>, are indicated by a <CODECLASS="literal">:</CODE>, as in this code:</P><PRECLASS="programlisting">use Getopt::Std;getopts(&quot;o:&quot;);if ($opt_o) {    print &quot;Writing output to $opt_o&quot;;}</PRE><PCLASS="para">Both <CODECLASS="literal">getopt</CODE> and <CODECLASS="literal">getopts</CODE> can take a second argument, a reference to a hash. If present, option values are stored in <CODECLASS="literal">$hash{X}</CODE> instead of <CODECLASS="literal">$opt_X</CODE>:</P><PRECLASS="programlisting">use Getopt::Std;%option = ();getopts(&quot;Do:&quot;, \%option);if ($option{D}) {    print &quot;Debugging mode enabled.\n&quot;;} # if not set, set output to &quot;-&quot;.  opening &quot;-&quot; for writing # means STDOUT $option{o} = &quot;-&quot; unless defined $option{o};                             print &quot;Writing output to file $option{o}\n&quot; unless $option{o} eq &quot;-&quot;;open(STDOUT, &quot;&gt; $option{o}&quot;)     or die &quot;Can't open $option{o} for output: $!\n&quot;;</PRE><PCLASS="para">You can specify some programs' options using full words instead of single characters. These options are (usually) indicated with two dashes instead of one:</P><PRECLASS="programlisting">% gnutar --extract --file latest.tar</PRE><PCLASS="para">The value for the <BCLASS="emphasis.bold">- -file</B> option could also be given with an equals sign:</P><PRECLASS="programlisting">% gnutar --extract --file=latest.tar</PRE><PCLASS="para">The Getopt::Long module's <CODECLASS="literal">GetOptions</CODE><ACLASS="indexterm"NAME="ch15-idx-1000005036-0"></A> function parses this style of options. It takes a hash whose keys are options and values are references to scalar variables:</P><PRECLASS="programlisting">use Getopt::Long;GetOptions( &quot;extract&quot; =&gt; \$extract,            &quot;file=s&quot;  =&gt; \$file );if ($extract) {    print &quot;I'm extracting.\n&quot;;}die &quot;I wish I had a file&quot; unless defined $file;print &quot;Working on the file $file\n&quot;;</PRE><PCLASS="para">If a key in the hash is just an option name, it's a Boolean option. The corresponding variable will be set to false if the option wasn't given, or to <CODECLASS="literal">1</CODE> if it was. <ACLASS="indexterm"NAME="ch15-idx-1000005224-0"></A><ACLASS="indexterm"NAME="ch15-idx-1000005224-1"></A>Getopt::Long provides fancier options than just the Boolean and value of Getopt::Std. Here's what the option specifier can look like:</P><TABLECLASS="informaltable"BORDER="1"CELLPADDING="3"><THEADCLASS="thead"><TRCLASS="row"VALIGN="TOP"><THCLASS="entry"ALIGN="LEFT"ROWSPAN="1"COLSPAN="1"><PCLASS="para">Specifier</P></TH><THCLASS="entry"ALIGN="LEFT"ROWSPAN="1"COLSPAN="1"><PCLASS="para">Value?</P></TH><THCLASS="entry"ALIGN="LEFT"ROWSPAN="1"COLSPAN="1"><PCLASS="para">Comment</P></TH></TR></THEAD><TBODYCLASS="tbody"><TRCLASS="row"VALIGN="TOP"><TDCLASS="entry"ROWSPAN="1"COLSPAN="1"><PCLASS="para"><CODECLASS="literal">option</CODE></P></TD><TDCLASS="entry"ROWSPAN="1"COLSPAN="1"><PCLASS="para">No</P></TD><TDCLASS="entry"ROWSPAN="1"COLSPAN="1"><PCLASS="para">Given as -  -<CODECLASS="literal">option</CODE

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -