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

时间:2016-07-12 20:34:36

标签: 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)

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

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

我需要填写未指定的fstype,例如具有“undef”值。 对我来说最好的解决方案就是获得哈希,比如......

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

有可能吗?谢谢。

2 个答案:

答案 0 :(得分:1)

直接使用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'
        };

答案 1 :(得分:0)

来自"参数回调" enter image description here的部分:

When applied to the following command line:
    arg1 --width=72 arg2 --width=60 arg3

This will call process("arg1") while $width is 80 , process("arg2") while $width is 72 , and process("arg3") while $width is 60.

编辑:根据要求添加MWE。

use strict;
use warnings;
use Getopt::Long qw(GetOptions :config permute);

my %mount_points;
my $filesystem;

sub process_filesystem_type($) {
    push @{$mount_points{$filesystem}}, $_[0];
}

GetOptions('t=s' => \$filesystem, '<>' => \&process_filesystem_type);

for my $fs (sort keys %mount_points) {
    print "$fs : ", join(',', @{$mount_points{$fs}}), "\n";
}

./ test -t nfs / abc / bcd -t ext4 / foo -t ntfs / bar / baz

  

ext4:/ foo

     

nfs:/ abc,/ bcd

     

ntfs:/ bar,/ baz

请注意,输入按文件系统类型排序,然后按挂载点排序。这与OP的解决方案相反。

相关问题