perl parse命令行选项

时间:2012-04-25 10:39:25

标签: 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

4 个答案:

答案 0 :(得分:6)

由于您处理简单的单词(而不是--switches),只需查看@ARGV,这是一个命令行选项的数组。对该数据应用简单的if / elsif / etc应该可以满足您的需求。

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

答案 1 :(得分: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';
}

答案 2 :(得分: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; }
}

答案 3 :(得分:0)

以下是我对此问题的看法

#!/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";}
}