perl:使用Getopt :: Long来设置Class :: Struct字段?

时间:2012-08-23 04:21:06

标签: perl getopt

我可以使用Getopt :: Long来设置结构字段吗?

use strict;
use diagnostics;
use Getopt::Long;
use Class::Struct foo [ a => '$', b => '$' ];

my $foo = foo->new();
GetOptions("a=i" => \$foo->a, "b=i" => \$foo->b);

似乎不起作用,“ - a 10”似乎没有设置$foo->a

显然,我宁愿避免

GetOptions("a=i" => sub { $foo->a($_[1]); }, ...);

另外,我宁愿将struct foo保持为数组,而不是哈希。

1 个答案:

答案 0 :(得分:5)

\$foo->a将引用$foo->a的返回值,这肯定不是您想要的。

你可以使用GetOptionsstore the values in a hash reference的功能,然后将其传递给对象的new

my $opt = {};
GetOptions($opt, 'a=i', 'b=i', ...)
my $foo = foo->new(%$opt);