在Perl中阅读可选的命令行参数 [英] Read optional command-line arguments in Perl
问题描述
我是Perl的新手,对它对可选参数的处理感到困惑.
I am new to Perl and I'm confused with its handling of optional arguments.
如果我有一个Perl脚本,该脚本使用类似于以下内容的代码来调用:
If I have a perl script that's invoked with something along the lines of:
plgrep [-f] < perl regular expression > < file/directory list >
我如何确定在命令行上是否给出了-f
运算符?
How would I determine whether or not the -f
operator is given or not on the command line?
推荐答案
传递给程序的所有参数都出现在数组@ARGV
中,因此您可以简单地检查任何数组元素是否包含字符串-f
All of the parameters passed to your program appear in the array @ARGV
, so you can simply check whether any of the array elements contain the string -f
但是,如果您要编写结合使用许多不同选项的程序,则可能会发现使用
But if you are writing a program that uses many different options in combination, you may find it simpler to use the Getopt::Long
module, which allows you to specify which parameters are optional, which take values, whether there are multiple synonynms for an option etc.
对GetOptions
的调用允许您指定程序期望的参数,并将从@ARGV
中删除命令行中出现的任何参数,并将指示符保存在简单的Perl变量中,以反映提供的内容和值,如果有的话,
A call to GetOptions
allows you to specify the parameters that your program expects, and will remove from @ARGV
any that appear in the command line, saving indicators in simple Perl variables that reflect which were provided and what values, if any, they had
例如,在您描述的简单情况下,您可以像这样编写代码
For instance, in the simple case that you describe, you could write your code like this
use strict;
use warnings 'all';
use feature 'say';
use Getopt::Long;
use Data::Dump;
say "\nBefore GetOptions";
dd \@ARGV;
GetOptions( f => \my $f_option);
say "\nAfter GetOptions";
dd $f_option;
dd \@ARGV;
输出
Before GetOptions
["-f", "regexp", "file"]
After GetOptions
1
["regexp", "file"]
因此您可以看到在调用GetOptions
之前,@ARGV
包含命令行中的所有数据.但是之后,-f
已被删除,变量$f_option
设置为1表示已指定该选项
So you can see that before the call to GetOptions
, @ARGV
contains all of the data in the command line. But afterwards, the -f
has been removed and variable $f_option
is set to 1 to indicate that the option was specified
这篇关于在Perl中阅读可选的命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!