【问题标题】:How to use GetOptions utility to handle 'optional' command-line arguments in Perl?如何使用 GetOptions 实用程序处理 Perl 中的“可选”命令行参数?
【发布时间】:2011-09-27 04:36:32
【问题描述】:

有许多 Perl 教程解释了如何使用 GetOptions 实用程序仅处理预期的命令行参数,否则退出并显示适当的消息。

在我的要求中,我有以下可选的命令行参数,例如,

  • -z zip_dir_path : 压缩输出
  • -h:显示帮助。

我尝试了一些与 GetOptions 的组合,但对我不起作用。
所以我的问题是:如何使用 GetOptions 来处理这个要求?

编辑:-z 需要'zip 目录路径'

编辑2: 我的脚本具有以下强制性命令行参数:

  • -in input_dir_path : 输入目录
  • -out output_dir_path : 输出目录

这是我的代码:

my %args;
GetOptions(\%args,
"in=s",
"out=s"
) or die &usage();

die "Missing -in!" unless $args{in};
die "Missing -out!" unless $args{out};

希望这个编辑增加更多的清晰度。

【问题讨论】:

  • 通常你打电话给GetOptions,然后看看你最终得到了什么,看看使用了哪些开关。也许您应该包括一些尝试来澄清发生了什么以及问题是什么。
  • @mu 太短:我已更新问题文本。感谢您的评论。

标签: perl command-line-arguments getopt-long


【解决方案1】:

这应该设置为 10 $zip_output$show_help 的值,具体取决于您在命令行中获得的输入参数。

use strict;
use warnings;

use Getopt::Long;

my $zip_output;
my $show_help;

GetOptions("z" => \$zip, "h" => \$show_help);

【讨论】:

  • @'Tudor Constantin':我更新了我的问题文本。谢谢你的回答。
【解决方案2】:

A : (colon) 可用于表示可选选项:

#!/usr/bin/env perl

use strict;
use warnings;

use Getopt::Long;

my ( $zip, $help, $input_dir, $output_dir );

GetOptions(
    'z:s'   => \$zip,
    'h'     => \$help,
    'in=s'  => \$input_dir,
    'out=s' => \$output_dir,
);

【讨论】:

  • 我认为,':' 可以用来表示该命令行开关的字符串值是可选的,而不是表示开关本身是可选的。我说的对吗?
  • 虽然我接受了@Alan Haggai Alavi 的回答,但同意@mu is too short 在他的评论中,GetOptions 用于列出用户提供的选项,脚本必须根据以下内容进一步处理参数需要。
【解决方案3】:

来自文档:

   : type [ desttype ]
       Like "=", but designates the argument as optional.  If omitted, an
       empty string will be assigned to string values options, and the
       value zero to numeric options.

如果您指定并检查空字符串,您就知道用户没有指定哪些字符串。

【讨论】:

    猜你喜欢
    • 2013-10-12
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    相关资源
    最近更新 更多