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 :: Descriptionモジュールをお勧めします。)

于 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 に答える