構成スクリプトを作成しようとしています。顧客ごとに変数を要求し、いくつかのテキスト ファイルを書き込みます。
ただし、各テキスト ファイルは複数回使用する必要があるため、上書きできません。各ファイルから読み取り、変更を加えてから、$name.originalname に保存することをお勧めします。
これは可能ですか?
構成スクリプトを作成しようとしています。顧客ごとに変数を要求し、いくつかのテキスト ファイルを書き込みます。
ただし、各テキスト ファイルは複数回使用する必要があるため、上書きできません。各ファイルから読み取り、変更を加えてから、$name.originalname に保存することをお勧めします。
これは可能ですか?
Template Toolkitのようなものが必要です。テンプレート エンジンでテンプレートを開き、プレースホルダーに入力して、結果を保存します。その魔法を自分で行う必要はありません。
非常に小さなジョブの場合、Text::Templateを使用することがあります。
最初にファイルをコピーしてから、コピーしたファイルを編集してみませんか
以下のコードは、各顧客の構成テンプレートを見つけることを想定しています。たとえば、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";
}
あるファイルを読み込み、行ごとに変更を加えてから、別のファイルに書き込みたいとします。
#!/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;