【发布时间】:2011-11-22 07:23:14
【问题描述】:
我有点搞砸了以下内容:
我有一个函数以下列方式调用子例程:
sub someFunction {
my $self = shift;
my $type = $self->{'type'};
if($type eq 'one_subroutine') {
$self->updateOneSubroutine();
}
elsif($type eq 'another_one_sub') {
$self->updateAnotherOneSub();
}
(...)
else {
die "Unsupported '$type'";
}
我必须改变它,让每个子例程都编码在自己的文件中,包括所有可用的文件,并自动调用里面的子例程。
我在测试文件中使用以下代码执行此操作:
# Assume a routines subdir with one_subroutine.pm file with
sub updateOneSubroutine(){
$self = shift;
$self->doSomeThings();
(...) #my code
}
1;
test.pl
# Saves in routines hash_ref a pair of file_name => subRoutineName for each file in routines subdir.
# This will be used later to call subroutine.
opendir(DIR,"lib/routines") or die "routines directory not found";
for my $filename (readdir(DIR)) {
if($filename=~m/\.pm$/){
# includes file
require "lib/routines/$filename";
# get rid of file extension
$filename=~s/(.*)\.pm/$1/g;
my $subroutine = "update_${file}";
# camelizes the subroutine name
$subroutine=~s/_([a-z0-9])/\u$1/g;
$routine->{ $filename } = $subroutine;
}
}
{
no strict "refs";
$routine->{$param}();
}
其中 param 类似于“one_subroutine”,与可用的文件名匹配。
由于每个子程序在调用中都会收到$self,所以我应该通过$self->something();来调用程序
我已经尝试过 $self->$routine->{$param}() 、 $self->${routine->${param}}() 和许多其他方法,但都没有成功。我检查了chapter 9 "dynamic subroutines" of mastering perl 和a similar question to perl monks,但我仍然无法弄清楚如何以代表 $self->updateAnotherOneSub() 的方式引用子例程,或者类似的方式让 $self 被读取为这些子程序中的参数。
提前致谢,凯伯。
【问题讨论】:
-
为什么
sub updateOneSubroutine () { ...中的原型是空的?如果这不是一个错字,那么它就是一个错误。
标签: perl dynamic this subroutine