使用 Getopt::Long 为同一个变量赋值

Assign values to same variable using Getopt::Long

我试图编写一个小的 perl 脚本来理解 Getopt::Long

脚本如下:

#!/usr/bin/perl

use strict;
use Getopt::Long;

my $op_type = "";
my @q_users;

GetOptions (
  'query' => $op_type = "query",
  'create' => $op_type = "create",
  'modify' => $op_type = "modify",
  'delete' => $op_type = "delete",
  'user=s' => \@q_users
) or usage ("Invalid options.");

print "operation : $op_type\n";

当我运行这个脚本如下图:

$ ./all_opt.pl --query
operation : delete

我假设我的程序中缺少某种中断语句。我期待 operation : query 作为结果。

请让我知道我在这里缺少什么。

您说得非常接近,但我认为您稍微误读了 Getopt::Long documentation。当找到一个选项时,您想要 运行 的任何代码都需要在子例程中。

#!/usr/bin/perl

use strict;
use Getopt::Long;

my $op_type = "";
my @q_users;

GetOptions (
  'query'  => sub { $op_type = 'query' },
  'create' => sub { $op_type = 'create' },
  'modify' => sub { $op_type = 'modify' },
  'delete' => sub { $op_type = 'delete' },
  'user=s' => \@q_users
) or usage ("Invalid options.");

print "operation : $op_type\n";

请注意,我刚刚在您现有的 $op_type = '...' 代码周围添加了 sub { ... }

说明您的代码的作用

您误解了语法。让我们添加一些括号来阐明 Perl 如何看待这段代码。

GetOptions(
  'query'  => ( $op_type = "query"  ),
  'create' => ( $op_type = "create" ),
  'modify' => ( $op_type = "modify" ),
  'delete' => ( $op_type = "delete" ),
  'user=s' => \@q_users
) or usage ("Invalid options.");

它会先运行括号内的赋值操作。每个 return 分配给 $op_type.

的值
$ perl -e 'print $foo = "bar"'
bar

由于他们都对同一个变量赋值,所以代码与此代码相同。

GetOptions(
  'query'  => "query",
  'create' => "create",
  'modify' => "modify",
  'delete' => "delete",
  'user=s' => \@q_users
) or usage ("Invalid options.");
$op_type = "delete";

GetOptions 希望您传递对变量的引用,以便它可以为您赋值给变量。但是你这样做只是为了 user\@q_users。其余的只是字符串。

最后,您打印的是 $op_type 的值,它始终具有上次赋值的值。正如我们在上面看到的,那是 delete。它不能是其他任何东西,因为 GetOptions 永远不会得到对 $op_type 的引用,所以它不能赋值。