【问题标题】:command line arguments in perl with keywordsperl 中带有关键字的命令行参数
【发布时间】:2013-12-10 11:17:24
【问题描述】:

我是 Perl 新手,目前我正在将命令行参数传递给 perl 脚本并通过 ARGS[0] 检索它。

perl <perlscript.pl> windows IE.

我想为上面提到的值赋予关键字。

perl <perlscript.pl> -os windows -browser IE -instance 2.

有时实例可能存在也可能不存在。我该如何在我的 perl 脚本中处理这个问题。

【问题讨论】:

    标签: perl command-line-arguments


    【解决方案1】:

    使用Getopt::Long 并将您的选项存储在哈希中:

    use warnings;
    use strict;
    use Getopt::Long qw(GetOptions);
    
    my %opt;
    GetOptions(\%opt, qw(
        os=s
        browser=s
        instance=i
    )) or die;
    

    【讨论】:

      【解决方案2】:

      有几个模块用于处理命令行参数:Getopt::DeclareGetopt::Long 可能是最流行的。在我的工作中,我们主要使用 Getopt::Declare,因此我将展示和示例,因为 @toolic 涵盖了 Getopt::Long。

      my $ARGS = Getopt::Declare->new(
         join("\n", 
              "[strict]",
              "-os       <string> The operating system [required]",
              "-browser  <string> The web browser      [required]",
              "-instance <int>    The instance"
         ) 
      ) or die;
      

      现在您可以通过 $ARGS 哈希访问任何参数。即$ARGS-&gt;{-os}

      [strict]严格解析命令行并报告任何错误。

      [required] 在选项声明之后意味着该字段必须存在,请注意我将其从实例中删除。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-23
        • 1970-01-01
        • 2021-08-24
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        • 2018-04-07
        相关资源
        最近更新 更多