代码之家  ›  专栏  ›  技术社区  ›  Milan Čížek

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

  •  3
  • Milan Čížek  · 技术社区  · 8 年前

    这是我在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'
            ];
    

    我需要用“undef”值填充未指定的fstype。 对我来说,最好的解决方案是得到哈希值,例如。。。

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

    有可能吗?非常感谢。

    2 回复  |  直到 8 年前
        1
  •  1
  •   stevieb    8 年前

    这不容易做到 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'
            };
    
        2
  •  1
  •   Community kfsone    4 年前

    docs :

    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

    分机4:/foo

    nfs:/abc,/bcd

    ntfs:/bar,/baz

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