Perl GetOpt::Long 带有可选参数的多个参数

标签 perl parsing parameters arguments getopt

这是我在 stackoverflow 上发表的第一篇文章。 :)

我正在尝试使用 GetOpt::Long 解决这种情况。

./myscript -m/abc -m/bcd -t nfs -m/ecd -t nfs ...

-m是挂载点,-t是文件系统的类型(可以放,但不是必须的)。

  Getopt::Long::Configure("bundling");
  GetOptions('m:s@' => \$mount, 'mountpoint:s@' => \$mount,
             't:s@' => \$fstype, 'fstype:s@'  => \$fstype)

这是不对的,我无法配对正确的安装和 fstype

./check_mount.pl -m /abc -m /bcd -t nfs -m /ecd -t nfs
$VAR1 = [
          '/abc',
          '/bcd',
          '/ecd'
        ];
$VAR1 = [
          'nfs',
          'nfs'
        ];

我需要填写未指定的文件类型,例如具有“undef”值。 对我来说最好的解决方案是获取哈希值,例如...

%opts;
$opts{'abc'} => 'undef'
$opts{'bcd'} => 'nfs'
$opts{'ecd'} => 'nfs'

这可能吗?谢谢。

最佳答案

直接用 Getopt::Long 做起来并不容易,但是如果你可以稍微改变参数结构,比如

./script.pl --disk /abc --disk /mno=nfs -d /xyz=nfs

...以下将带您到达您想要的位置(请注意,缺少的类型将显示为空字符串,而不是 undef):

use warnings;
use strict;

use Data::Dumper;
use Getopt::Long;

my %disks;

GetOptions(
    'd|disk:s' => \%disks, # this allows both -d and --disk to work
);

print Dumper \%disks;

输出:

$VAR1 = {
          '/abc' => '',
          '/mno' => 'nfs',
          '/xyz' => 'nfs'
        };

关于Perl GetOpt::Long 带有可选参数的多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38338421/

相关文章:

perl - 如何在 Perl 中不活跃

json - Perl 解析 JSON 代码 - 为什么我的路径错误?

javascript - 如果 AngularJS 匹配一个值,它会在加载时更改单个 URL 参数

programming-languages - 什么语言可以让我们得到定义的参数名和传递的参数名?

perl - 如何基于现有数组的一部分形成一个新数组

perl - 在不知道模块名但知道文件名的情况下加载和使用perl模块

perl - Perl模棱两可的命令行选项,以及-i对eval的安全性影响?

c# - 如何使用 C# .NET 从 XML 字符串中读取处理指令?

c++ - 如何加速包含图形数据的文本文件的 io/解析

C# - 如果未提供字节数组,如何传递空值?