Perl 如何以编程方式创建新的CGI脚本并立即运行它?
我已经编写了一个Perl脚本来读取配置文件并创建CGI脚本。这很好,我在终端上得到CGI脚本的输出,我可以在网页上执行CGI脚本。下面是我的示例脚本Perl 如何以编程方式创建新的CGI脚本并立即运行它?,perl,cgi,Perl,Cgi,我已经编写了一个Perl脚本来读取配置文件并创建CGI脚本。这很好,我在终端上得到CGI脚本的输出,我可以在网页上执行CGI脚本。下面是我的示例脚本 #!/usr/bin/perl -w use strict; use Text::Template; my $conf = "test.cfg"; open CFG, $conf or die "Could not open config file"; my @rawConfig = <CFG>; my $config = eva
#!/usr/bin/perl -w
use strict;
use Text::Template;
my $conf = "test.cfg";
open CFG, $conf or die "Could not open config file";
my @rawConfig = <CFG>;
my $config = eval "{".join("",@rawConfig)."}";
my $template = Text::Template->new(TYPE => 'FILE', SOURCE => 'test.cgi.tmpl');
my $result = $template->fill_in(HASH => $config);
print $result;
#/usr/bin/perl-w
严格使用;
使用文本::模板;
my$conf=“test.cfg”;
打开CFG,$conf或die“无法打开配置文件”;
my@rawConfig=;
我的$config=eval“{”.join(“,@rawConfig)。“}”;
my$template=Text::template->new(类型=>'FILE',源=>'test.cgi.tmpl');
my$result=$template->fill_in(散列=>$config);
打印$result;
通过使用它,我必须保存每个CGI并分别执行。我需要帮助修改这段代码,以便我可以直接在web上执行此脚本并在网页上显示输出。这是一件非常非常可怕的事情,我通常建议不要做任何创建新程序并让世界在没有人的情况下运行它们的事情 然而,我怀疑您这样做可能是因为您正在创建的CGI脚本只需要不同的配置数据,并且您已经将这些数据存储在脚本本身中。这只是一个猜测,但这通常是这类事情的动机。答案是不要在脚本中存储配置数据。我有一整章是关于不在代码中存储配置的 我会努力避免你所描述的情况 (?) 如果您确实需要这样做是有充分的理由的(这几乎从来没有发生过),那么您可以从原始流程创建文件,然后向新的CGI脚本发出内部重定向。你怎么做是你的家庭作业,因为我不会替你把子弹射进枪里。
多个基于模板的脚本(几乎)永远都不是正确答案 使用配置文件中的数据结构和控制结构来获得所需的行为 而不是使用模板创建代码,如:
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);