perl - 如何使用 GetOptions 实用程序处理 Perl 中的 'optional' 命令行参数?

标签 perl command-line-arguments getopt-long

有许多 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};
    

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

    最佳答案

    A : (colon)可用于指示 optional :

    #!/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,
    );
    

    关于perl - 如何使用 GetOptions 实用程序处理 Perl 中的 'optional' 命令行参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6555644/

    相关文章:

    perl - 如何在 Perl 中检查今天是星期一?

    regex - 为什么我只得到第一个捕获组?

    command-line - 通过命令行将文件名作为字符串传递到 Maple 中

    Python 将多个字符串传递给单个命令行参数

    eclipse - 在 Eclipse CDT 中无法解析 getopt_long

    perl - 使用 Perl 打开并读取大量具有相同结尾的文件

    arrays - 在 perl 中为数组内的所有元素添加引号

    c++ - 为随机和用户输入的 C++ 代码处理命令行参数

    c - getopt 不解析参数的可选参数

    perl - 强制使用标志 Getopt::Long