3

我正在尝试编写配置脚本。对于每个客户,它会询问变量,然后编写几个文本文件。

但是每个文本文件都需要多次使用,所以不能覆盖它们。我希望它从每个文件中读取,进行更改,然后将它们保存到 $name.originalname。

这可能吗?

4

4 回答 4

4

您想要类似Template Toolkit的东西。您让模板引擎打开一个模板,填写占位符,然后保存结果。你不应该自己做任何魔法。

对于非常小的工作,我有时会使用Text::Template

于 2010-01-16T17:13:57.840 回答
1

为什么不先复制文件,然后编辑复制的文件

于 2010-01-15T12:14:01.123 回答
0

下面的代码希望为每个客户找到一个配置模板,例如 Joe 的模板所在的位置,joe.originaljoe并将输出写入joe

foreach my $name (@customers) {
  my $template = "$name.original$name";
  open my $in,  "<", $template or die "$0: open $template";
  open my $out, ">", $name     or die "$0: open $name";

  # whatever processing you're doing goes here
  my $output = process_template $in;

  print $out $output           or die "$0: print $out: $!";

  close $in;
  close $out                   or warn "$0: close $name";
}
于 2010-01-15T14:36:08.410 回答
0

假设您要读取一个文件,逐行对其进行更改,然后写入另一个文件:

#!/usr/bin/perl

use strict;
use warnings;

# set $input_file and #output_file accordingly

# input file
open my $in_filehandle, '<', $input_file or die $!;
# output file
open my $out_filehandle, '>', $output_file or die $!;

# iterate through the input file one line at a time
while ( <$in_filehandle> ) {

    # save this line and remove the newline
    my $input_line = $_;
    chomp $input_line;

    # prepare the line to be written out
    my $output_line = do_something( $input_line );

    # write to the output file
    print $output_line . "\n";

}

close $in_filehandle;
close $out_filehandle;
于 2012-09-15T03:14:46.630 回答