代码之家  ›  专栏  ›  技术社区  ›  Space

如何以编程方式创建新的CGI脚本并立即运行它?

  •  0
  • Space  · 技术社区  · 16 年前

    我编写了一个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 = eval "{".join("",@rawConfig)."}";
    
    my $template = Text::Template->new(TYPE => 'FILE',  SOURCE => 'test.cgi.tmpl');
    my $result = $template->fill_in(HASH => $config);
    print $result;
    

    通过使用它,我必须保存每个CGI并分别执行。我需要帮助来修改这个代码,这样我就可以直接在Web上执行这个脚本并在网页上显示输出。

    2 回复  |  直到 16 年前
        1
  •  2
  •   daotoad    16 年前

    多个基于模板的脚本(几乎)永远都不是正确的答案。

    使用配置文件中的数据结构和控制结构来获得所需的行为。

    而不是使用模板创建类似以下代码的代码:

    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);
    

    通过生成包含config info的闭包,可以将config info绑定到子例程(即“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);
    
        2
  •  6
  •   Community Mohan Dere    9 年前

    这是一件非常,非常可怕的事情,我通常建议不要做任何创建新程序的事情,让世界在没有人的情况下运行它们。

    不过,我怀疑您这样做可能是因为您创建的CGI脚本只需要不同的配置数据,而您已经将其存储在脚本本身中了。这只是一个猜测,但它通常是这类事情的动力。答案是不要在脚本中存储配置数据。我有一整章 Mastering Perl 关于不在代码中存储配置。

    我会努力避免你描述的情况。

    ( Does SO have a spoiler tag ?)

    如果您真的需要这样做是出于一个好的理由(而且几乎从来没有这样做过),那么您将从原始进程创建文件,然后发出一个内部重定向到新的CGI脚本。你怎么做是你的家庭作业,因为我不会帮你把子弹放进枪里。

    推荐文章