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

标签 perl 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 - 使用 Getopt::Long 为同一变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38846414/

相关文章:

linux - 查找包含并替换为的行

perl - 嵌套的 perl 数组和散列和引用

arrays - 在perl中查找元素的位置

java - Perl 和 Java 之间通过套接字发送字节数组

c - 在 C 中使用带有非选项参数的 getopt

perl - 为什么我不能在 Perl 中对数组使用菱形运算符?

使用 getopt() : giving command line flags criteria 进行 C 编程

c - 无效长选项的段错误

c - 如何在 C 编程 getopt_long 中将转义序列(如制表符和换行符)作为命令行参数传递?

c++ - aix 7.1 中缺少 getopt.h