2012-04-25 39 views
0

我想从命令行获取参数并解析它,如果参数正确,请调用基于它的某些函数。我是perl的新手,可以让一个人知道如何实现这一点perl解析命令行选项

script.pl aviator #switch is valid and should call subroutine aviator() 
script.pl aviator debug #valid switch and should call subroutine aviator_debug 
script.pl admin debug or script.pl debug admin #valid switch and should call subroutine admin_debug() 
script.pl admin #valid switch and should call subroutine admin() 
script.pl dfsdsd ##invalid switch ,wrong option 

回答

2

变体1:

#!/usr/bin/perl 

my $command=join(' ',@ARGV); 
if ($command eq 'aviator') { &aviator; } 
elsif ($command eq 'aviator debug' or $command eq 'debug aviator') { &aviator_debug; } 
elsif ($command eq 'admin debug' or $command eq 'debug admin') { &admin_debug; } 
elsif ($command eq 'admin') { &admin; } 
else {print "invalid option ".$command."\n";exit;} 

变体2:

#!/usr/bin/perl 

if (grep /^aviator$/, @ARGV) { 
    if (grep /^debug$/, @ARGV) { &aviator_debug; } 
    else { &aviator; } 
} elsif (grep /^admin$/, @ARGV) { 
    if (grep /^debug$/, @ARGV) { &admin_debug; } 
    else { &admin; } 
} else { print "invalid option ".join(' ',@ARGV)."\n";exit;} 
exit; 

变体3:

#!/usr/bin/perl 
use Switch; 

switch (join ' ',@ARGV) { 
    case 'admin' { &admin();} 
    case 'admin debug' { &admin_debug; } 
    case 'debug admin' { &admin_debug; } 
    case 'aviator' { &aviator; } 
    case 'aviator debug' { &aviator_debug; } 
    case 'debug aviator' { &aviator_debug; } 
    case /.*/ { print "invalid option ".join(' ',@ARGV)."\n";exit; } 
} 
+0

什么会发生在参数之间的无限空格.. – Rajeev 2012-04-25 10:54:51

+0

@ARGV没有空格。无限空间自动从中删除 – askovpen 2012-04-25 10:57:47

+0

如何管理调试或调试管理员照顾与这种case.which是有效的.... – Rajeev 2012-04-25 11:17:14

6

由于您使用的是纯字(而不是--switches),因此请查看@ARGV,它是命令行选项的数组。对这些数据应用简单的if/elsif/etc应该满足您的需求。

(对于更复杂的要求,我建议的Getopt::Long::Descriptive模块。)

0

H这是我对问题的看法

#!/usr/bin/perl 
use 5.14.0; 

my $arg1 = shift; 
my $arg2 = shift; 

given ($arg1) { 
    when ($arg1 eq 'aviator') {say "aviator"} 
    when ($arg1 eq 'admin' && !$arg2) {say "admin"} 
    when ($arg1 =~ /^admin|debug$/ && $arg2 =~ /^admin|debug$/) {say "admin debug"} 
    default {say "error";} 
} 
4

对特定字符串进行大量检查是维护恶梦的秘诀,因为您的系统越来越复杂。我强烈建议实施某种调度表。

#!/usr/bin/perl 

use strict; 
use warnings; 
use 5.010; 

my %commands = (
    aviator  => \&aviator, 
    aviator_debug => \&aviator_debug, 
    admin   => \&admin, 
    admin_debug => \&admin_debug, 
    debug_admin => \&admin_debug, 
); 

my $command = join '_', @ARGV; 

if (exists $commands{$command}) { 
    $commands{$command}->(); 
} else { 
    die "Illegal options: @ARGV\n"; 
} 

sub aviator { 
    say 'aviator'; 
} 

sub aviator_debug { 
    say 'aviator_debug'; 
} 

sub admin { 
    say 'admin'; 
} 

sub admin_debug { 
    say 'admin debug'; 
}