2016-07-12 3 views
3

이것은 내 주먹 stackoverflow 게시물입니다. :)Perl GetOpt :: 선택 매개 변수가있는 복수 인수

나는이 시나리오를 GetOpt :: Long으로 풀려고한다.

./myscript -m/ABC -m/BCD -t NFS -m/ECD -t NFS ...

-m 배치 될 수있다 (포인트 및 -t 파일 시스템의 타입이 장착하고, 하지만 필수는 아닙니다).

Getopt::Long::Configure("bundling"); 
    GetOptions('m:[email protected]' => \$mount, 'mountpoint:[email protected]' => \$mount, 
      't:[email protected]' => \$fstype, 'fstype:[email protected]' => \$fstype) 

이 잘하지, 난 할 수 쌍 적절한 마운트 아니에요 내가 예를 들어, 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' 

그것이 가능 등 ... 같은 해시받을 것 ? 고맙습니다. docs의 "인수 콜백"섹션에서

+0

옵션에 대해 매우 구체적인 명령을 시행하려고 시도하지만 매우 일반적이거나 직관적이라고 생각하지 않습니다. 만약 내가 당신의 응용 프로그램 사용자라면'-m foo -t bar'가'-t bar -m foo'와 같을 것이라고 생각합니다. Getopt :: Long을 사용하여이 작업을 수행 할 수는 있지만 다른 디자인이 더 좋을 것이라고 생각합니다. – ThisSuitIsBlackNot

답변

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

[스스로 분리 할 필요조차 없습니다.] (http : //perldoc.perl.org/Getopt/Long.html # Options with-hash-values)'='를 포함하는 마운트 포인트를주의하십시오. – ThisSuitIsBlackNot

+0

좋은 전화 @ThisSuitIsBlack 아니요 ... 어떻게 든 내 년 동안 문서 섹션을 놓쳤습니다 :) 편리합니다! (답변이 업데이트 됨) – stevieb

0

:

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/바/바즈

ext4를 :/foo는

NFS :/ABC/BCD

NTFS/바/입력 한 다음 파일 시스템 유형 마운트 지점으로 정렬되어 있습니다 바즈

참고. 이것은 OP의 해결책과 반대입니다.

+1

OP 질문에 기초한 작업 예제를 제공하면 아마도 도움이 될 것입니다 ... – stevieb

+0

@stevieb 요청에 따라 MWE를 추가했습니다. 아마 전에 그렇게 했어야했는데, 게으르다. – Tim

+0

해줘서 고마워요! –

관련 문제