简体   繁体   English

如何在perl中传递命令行参数以获取getopt

[英]how to pass command line arguments to getopt in perl

I am new to Perl. 我是Perl的新手。 I have to pass command line arguments to GetOptions method so I can access those variables. 我必须将命令行参数传递给GetOptions方法,以便可以访问这些变量。 I have tried the following code: 我尝试了以下代码:

  use Getopt::Long;
  $result = GetOptions($ARGV[0] => \$serv_name, $ARGV[1] => \$serv_id);
  print "Server name is $serv_name & server id is $serv_id";

But I am not getting desired output. 但是我没有得到想要的输出。 So how do I do this? 那么我该怎么做呢?

Try this (inspired from documentation of Getopt::Long ): 试试这个(从Getopt :: Long的文档中得到启发):

use Getopt::Long;

GetOptions(
    "server_id=i"   => \my $serv_id,     # numeric
    "server_name=s" => \my $serv_name,   # string
) or die "Error in command line arguments\n";

print "Server name is $serv_name & server id is $serv_id\n";

If server_id argument maybe not numeric, change "server_id=i" to "server_id=s" 如果server_id参数可能不是数字, "server_id=i"更改为"server_id=s"

And call the program these ways: 并通过以下方式调用程序:

%> perl ex.pl --server_name=the_name --server_id=1234
# or
%> perl ex.pl -server_name the_name -server_id 1234

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM