2015-11-28 255 views
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>,.... 

关于如何做到这一点的任何建议?

+3

你是什么意思“这不行”? '$ obj - > $ method(@args)'是有效的Perl。 – choroba

回答

2

根据perlobj方法调用可以使用字符串变量。

$object->$method(@args); 

所以你foreach环路应该已经工作得很好。或者这一个,这是罗嗦要少得多:

use strict; 
use warnings; 

my $hex = Hexagram->new(); 
gather_info($hex, $_) 
    for qw/top bot chinese title meaning/; 

sub gather_info { 
    my ($hex, $method) = @_; 

    print "What is $method?\n"; 
    my $response = <STDIN>; 
    chomp $response; 
    $hex->$method($response); 
} 

确保已strictwarnings启用你,然后再试一次。更新你的帖子有错误等。