0

我正在尝试从命令行获取参数并对其进行解析,如果参数正确,则基于它调用某些函数。我是 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

4 回答 4

6

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

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

于 2012-04-25T10:41:37.943 回答
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';
}
于 2012-04-25T16:05:47.833 回答
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; }
}
于 2012-04-25T10:49:15.620 回答
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";}
}
于 2012-04-25T11:41:30.870 回答