2014-03-25 2 views
2

Getopt :: Long을 사용하여 알 수없는 옵션을 어떻게 인식 할 수 있습니까? Perl에서 알 수없는 옵션 Getopt :: Long

나는 '<>'시도하지만 expected..Consider 작동하지 않았다

use Modern::Perl; 
use Getopt::Long; 

my $help=''; 
GetOptions ('help' => \$help,'<>' => \&usage); 
usage() if $help; 

usage() if @ARGV != 1; 

my $fn=pop; 

say "FileName: $fn"; 

sub usage { 
    say "Unknown option: @_" if (@_); 
    say "Usage: $0 <filename>"; 
    say "  $0 --help"; 
    say ""; 
    exit 
} 

나는이 경우 알 수없는 옵션 (있는 경우에만 다음, 다른 것을 Unknown option를 인쇄하고 싶습니다 --help). 그러나 이제는 파일 이름이 인식 할 수없는 옵션이라고 생각합니다.

+0

것은 당신이 인쇄 할 건가요'알 수없는 옵션 여기

이 예제 스크립트입니다 : 그것을 달성하기 위해 헬퍼 메소드를 작성하지 않고도 원하는 동작을받을 수 '- foo' 나'-foo' 같은 것을'foo'를 파일 이름으로 취급합니까? – ThisSuitIsBlackNot

답변

4

에 실패하면 usage 함수를 호출하십시오. Getopt::Long 당신을 위해 (STDERR에) Unknown option 인쇄됩니다 : 아주 잘 함께 핵심 모듈 Getopt::LongPod::Usage 작품으로 포드 문서를 사용

use Modern::Perl; 
use Getopt::Long; 

my $help=''; 
GetOptions ('help' => \$help) or usage(); 
usage() if $help; 

usage() if @ARGV != 1; 

my $fn=pop; 

say "FileName: $fn"; 

sub usage { 
    say "Usage: $0 <filename>"; 
    say "  $0 --help"; 
    say ""; 
    exit 
} 
+0

우우 (Uou)는 실수로 성공을 돌려 주어야합니다. – ikegami

4

시작.

#!/usr/bin/perl 

use File::Basename qw(basename); 
use Getopt::Long qw(GetOptions); 
use Pod::Usage qw(pod2usage); 
use Readonly; 
use version; 

use strict; 
use warnings; 

Readonly my $VERSION => qv('0.0.1'); 
Readonly my $EXE => basename($0); 

GetOptions(
    'version' => \my $version, 
    'usage'  => \my $usage, 
    'help|?' => \my $help, 
    'man'  => \my $man, 
) or pod2usage(-verbose => 0); 
pod2usage(-verbose => 0) if $usage; 
pod2usage(-verbose => 1) if $help; 
pod2usage(-verbose => 2) if $man; 

if ($version) { 
    print "$EXE v$VERSION\n"; 
    exit; 
} 

## Check for File 
pod2usage("$EXE: No filename specified.\n") unless @ARGV; 

my $file = $ARGV[0]; 
pod2usage("$EXE: $file is a directory.\n") if -d $file; 
pod2usage("$EXE: $file is not writable.\n") if !-w $file; 


#.... 
print "Hello World\n"; 
#.... 

1; 

__END__ 

=head1 NAME 

hello.pl - Mirrors a script using pod 

=head1 SYNOPSIS 

./hello.pl [FILE] 


=head1 OPTIONS 

=over 4 

=item --version 

Print the version information 

=item --usage 

Print the usage line of this summary 

=item --help 

Print this summary. 

=item --man 

Print the complete manpage 

=back 


=head1 DESCRIPTION 

Sometimes a programmer just enjoys a bit of documentation. 
They can't help themselves, it makes them feel accomplished. 

=head1 AUTHOR 

Written by A Simple Coder 

출력 :

>perl hello.pl --test 
Unknown option: test 
Usage: 
    ./hello.pl [FILE] 
+0

+1 감사합니다. 나는 펄을 배우기 시작 했으므로 POD 문서화에 대해 잘 알지 못했다. –

관련 문제