2012-04-25 76 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'; 
}