0

我正在创建一个 perl 脚本来转换模板文件 () 中的命令列表,并将它们输出到输出文件 () 中不同格式的另一个文件。

模板文件中的命令如下所示:

command1 --max-size=2M --type="some value"

我在从该字符串中提取选项和值时遇到了一些问题。到目前为止,我有:

m/(\s--\w*=)/ig

哪个会返回:

" --max-size="
" --type="

但是我不知道如何将选项和值作为单独的变量返回,或者如何适应引号的使用。

谁能引导我朝着正确的方向前进?

旁注:我知道 Getops 在从命令行执行此操作方面做得很棒,但不幸的是这些命令作为字符串传递:(

4

3 回答 3

3

Getopt::Std还是Getopt::Long

你看过这个选项还是这个选项?

似乎没有理由重新发明轮子。

于 2012-11-17T23:19:34.343 回答
0

下面的代码产生

@args = ('command1', '--max-size=2M', '--type=some value');

适合传递GetOptions如下:

local @ARGV = @args;
GetOptions(...) or die;

最后,代码:

for ($cmd) {
   my @args;
   while (1) {
      last if /\G \s* \z /xgc;

      /\G \s* /xgc;

      my $arg;
      while (1) {
         if (/\G ([^\\"'\s]) /xgc) {
            $arg .= $1;
         }
         elsif (/\G \\ /xgc) {
            /\G (.) /sxgc
               or die "Incomplete escape";

            $arg .= $1;
         }
         elsif (/\G (?=") /xgc) {
            /\G " ( (?:[^"\\]|\\.)* ) " /sxgc
               or die "Incomplete double-quoted arging";

            my $quoted = $1;
            $quoted =~ s/\\(.)/$1/sg;

            $arg .= $quoted;
         }
         elsif (/\G (?=') /xgc) {
            /\G ' ( [^']* ) ' /xgc
               or die "Incomplete single-quoted arging";

            $arg .= $1;
         }
         else {
            last;
         }
      }

      push @args, $arg;
   }

   @args
      or die "Blank command";

   ...
}
于 2012-11-17T14:13:42.703 回答
0
use Data::Dumper;
$_ = 'command1 --max-size=2M a=ignore =ignore --switch --type="some value" --x= --z=1';
my %args;
while (/((?<=\s--)[a-z\d-]+)(?:="?|(?=\s))((?<![="])|(?<=")[^"]*(?=")|(?<==)(?!")\S*(?!"))"?(?=\s|$)/ig) {
  $args->{$1} = $2;
}
print Dumper($args);

---

$VAR1 = {
          'switch' => '',
          'x' => '',
          'type' => 'some value',
          'z' => '1',
          'max-size' => '2M'
        };

(在这里测试这个演示)

于 2012-11-17T13:54:38.117 回答