如何将命令行参数传递给 Perl 程序? [英] How can I pass command-line arguments to a Perl program?
问题描述
我正在编写 Perl 脚本.如何将命令行参数传递给它?
I'm working on a Perl script. How can I pass command line parameters to it?
示例:
script.pl "string1" "string2"
推荐答案
取决于你想做什么.如果你想使用这两个参数作为输入文件,你可以直接传入它们,然后使用 <>
读取它们的内容.
Depends on what you want to do. If you want to use the two arguments as input files, you can just pass them in and then use <>
to read their contents.
如果它们有不同的含义,您可以使用 GetOpt::Std
和 GetOpt::Long
轻松处理它们.GetOpt::Std
仅支持单字符开关,GetOpt::Long
更加灵活.来自 GetOpt::Long
:
If they have a different meaning, you can use GetOpt::Std
and GetOpt::Long
to process them easily. GetOpt::Std
supports only single-character switches and GetOpt::Long
is much more flexible. From GetOpt::Long
:
use Getopt::Long;
my $data = "file.dat";
my $length = 24;
my $verbose;
$result = GetOptions ("length=i" => $length, # numeric
"file=s" => $data, # string
"verbose" => $verbose); # flag
或者,@ARGV
是一个包含所有命令行参数的特殊变量.$ARGV[0]
是第一个(即 "string1"
在您的情况下), $ARGV[1]
是第二个参数.您不需要特殊的模块来访问 @ARGV
.
Alternatively, @ARGV
is a special variable that contains all the command line arguments. $ARGV[0]
is the first (ie. "string1"
in your case) and $ARGV[1]
is the second argument. You don't need a special module to access @ARGV
.
这篇关于如何将命令行参数传递给 Perl 程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!