我正在尝试编写一个配置脚本。 对于每个客户,它会询问变量,然后编写几个文本文件。Perl:打开一个文件并在编辑后以不同的名称保存
但是每个文本文件都需要多次使用,所以不能覆盖它们。我更喜欢它从每个文件读取,进行更改,然后将它们保存到$ name.originalname。
这可能吗?
我正在尝试编写一个配置脚本。 对于每个客户,它会询问变量,然后编写几个文本文件。Perl:打开一个文件并在编辑后以不同的名称保存
但是每个文本文件都需要多次使用,所以不能覆盖它们。我更喜欢它从每个文件读取,进行更改,然后将它们保存到$ name.originalname。
这可能吗?
下面的代码希望为每个客户找到一个配置模板,其中,例如,乔的模板是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";
}
我已经想通了一些东西:我忘了perl不像......“流”像其他脚本。我卡住了 $ customer_name =“placeholder”;那里有 ,并且有一个名为CPE_Option_A.txt.placeholder的文件。 所以我认为问题是我必须确保它最后复制文件。 – Soop 2010-01-15 15:01:33
你想要类似Template Toolkit。您让模板引擎打开模板,填充占位符并保存结果。你不应该自己做任何魔法。
对于非常小的工作,我有时使用Text::Template。
假设你想在一个文件中读取,进行更改行由行,然后写入到另一个文件:
#!/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;
这不是很清楚。你能告诉我们“多次使用”的意思吗,你试过了什么 – 2010-01-15 12:07:31
我还没有试过任何东西,我正在计划。 “多次使用”表示不同变量组的相同文件。 因此它需要保持不变。 – Soop 2010-01-15 12:44:28