gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:52:10 25 4
gpt4 key购买 nike

我试图编写一个小的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com