【问题标题】:How to use Getopt::Long method?如何使用 Getopt::Long 方法?
【发布时间】:2010-06-30 11:04:06
【问题描述】:

如果输入命令执行是这样的,我该如何使用Getopt::Long方法:

$ testcmd -option check  ARG1 ARG2 ARG3

$ testcmd  ARG1 ARG2 ARG3

【问题讨论】:

  • 这取决于你想用这些选项和标志做什么。下面回答的人正在努力做出最好的猜测,但读心术是一项很难掌握的技能。

标签: perl getopt-long


【解决方案1】:

一个简单的例子:

#! /usr/bin/perl

use warnings;
use strict;

use Getopt::Long;

sub usage { "Usage: $0 [--option=VALUE] ARG1 ARG2 ARG3\n" }

my $option = "default";

GetOptions("option=s", \$option)
  or die usage;

die usage unless @ARGV == 3;

print "$0: option=$option: @ARGV\n";

Getopt::Long 接受的内容非常灵活:

$ ./cmd
用法:./cmd [--option=VALUE] ARG1 ARG2 ARG3

$ ./cmd 1 2 3
./cmd:选项=默认值:1 2 3

$ ./cmd --option=foo 4 5 6
./cmd: 选项=foo: 4 5 6

$ ./cmd -option=bar 7 8 9
./cmd:选项=栏:7 8 9

$ ./cmd -option 检查 a b c
./cmd: option=check: a b c

【讨论】:

    【解决方案2】:

    您需要启用pass_through 选项。下面引用的文档:

    pass_through(默认:禁用)

    未知、模棱两可或 提供了无效的选项值 在@ARGV 中传递而不是 被标记为错误。这使它 可以编写包装脚本 仅处理用户提供的部分内容 命令行参数,并传递 其他人的剩余选择 程序。

    如果启用require_order,选项 处理将在第一个终止 无法识别的选项,或非选项, 以先到者为准。然而,如果 permute 改为启用,结果 可能会变得混乱。

    DVK's posted an example 如何在另一个答案中执行此操作。如果您觉得他的回答有用,我会先投票赞成。

    【讨论】:

    • +1 用于识别需要传递以“-”开头的值
    【解决方案3】:
    #!/usr/bin/perl
    
    use Getopt::Long;
    
    my $cla = GetOptions (  "one=s"         =>      \$one,
                            "two=s"         =>      \$two,
                            "three=s"       =>      \$three,
                            "help|h|?"      =>      \$help,
    ) or usage ();
    
    if ($help) {
            usage ();
    }
    
    my $first = $one;
    my $second = $two;
    my $third = $three;
    
    printf ("%-7s %-9s %-7s\n", $first, $second, $third);
    
    sub usage {
            print "\n$0\t" . "[ -one <text> -two <text> -three <text> ]\n\n";
            exit (0);
    }
    

    【讨论】:

    • 也许你应该在你的代码中添加一些解释,这样它会更有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 2013-11-03
    • 1970-01-01
    相关资源
    最近更新 更多