多个基于模板的脚本(几乎)永远不是正确答案。
使用配置文件中的数据结构和控制结构来获得您需要的行为。
而不是使用模板来创建类似的代码:
sub foo {
my $thing = shift;
return blarg( $thing ) * feemb( $thing );
}
sub bar {
my $thing = shift;
return crag( $thing ) * forg( $thing );
}
sub baz {
my $thing = shift;
return chomb( $thing ) * veezle( $thing );
}
这样做:
# Get this from a config file. YAML perhaps
my $cfg = {
foo => [ \&blarg, \&feemb ],
bar => [ \&crag, \&forg ],
baz => [ \&chomb, \&veezle ],
};
sub calculate_product {
my $cfg = shift;
my $type = shift;
my $thing = shift;
my @subs_to_call = @{ $cfg->{$type} || [] };
my $result = {shift @subs_to_call}->($thing};
$result *= $_->($thing) for @subs_to_call;
return $result;
}
# Call like so:
my $foo_prod = calculate_product($cfg, 'foo', 15);
您可以通过使用配置信息生成闭包来将配置信息绑定到子例程(即'curry your functions'):
# Get this from a config file. YAML perhaps
my $cfg = {
foo => [ \&blarg, \&feemb ],
bar => [ \&crag, \&forg ],
baz => [ \&chomb, \&veezle ],
};
my %calculate_product;
for my $product ( keys %$cfg ) {
my @stored_subs_to_call = @{$cfg->{$product} || [] };
$calculate_product{$prod} = sub {
my $thing = shift;
my @subs_to_call = @stored_subs_to_call;
my $result = {shift @subs_to_call}->($thing};
$result *= $_->($thing) for @subs_to_call;
return $result;
}
}
# Call generated code like so:
my $foo_prod = $calculate_product{foo}->(15);