2
我创造了这样一个对象作为如何遍历
my $hex = Hexagram->new();
对Perl对象的方法,它有多种方法:
top
bot
chinese
title
meaning
此对象将创造了无数次,每次我需要收集和测试上述每种方法的信息。
我想这样做
foreach my $method (qw/top bot chinese title meaning/)
{
&gather_info($hex,$method);
}
,然后有一些像
sub gather_info {
my ($hex,$method) = @_;
print "What is the $method? ";
my $response = <STDIN>;
chomp $response;
$hex->${method}($reponse);
.... and other actions ....
}
但是,这是行不通的。相反,对于每种方法,我似乎必须一次又一次地写出基本的代码结构,这看起来简单浪费。
我也试过的东西,我试图传递给方法调用的参考,如
foreach my $ra ([\$hex->top, "top"],
[\$hex->bot, "bot"],....)
{
my ($object_method, $name) = @{$ra};
&rgather_info($object_method, $name);
}
其中
sub $gather_info {
my ($rhex, $name) = @_;
print "What is the $name?";
my $response = <STDIN>;
chomp $response;
&{$rhex}($response);
.... and other actions ....
}
但是这一次我得到
错误Not a CODE reference at <program name> line <line number>,....
关于如何做到这一点的任何建议?
你是什么意思“这不行”? '$ obj - > $ method(@args)'是有效的Perl。 – choroba