Use a loop such as below. Write the header and the footer outside the loop. I refactored the code slightly to fit best Perl practices, but otherwise your code is OK. Note that you open your output file for appending. Not sure if that's intended. Perhaps you mean to open for writing: open my $out_fh, '>', $new_sample_file or die $!;
use strict;
use warnings;
my $sample_file = "/output_files/sample.txt";
my $new_sample_file = "/output_files/sample_new.txt";
my $header = <<EOF;
a
b
c
EOF
my $footer = <<EOF;
x
y
z
EOF
open my $out_fh, '>>', $new_sample_file or die $!;
print {$out_fh} $header;
for my $num_samples ( 1..3 ) {
open my $in_fh, '<', $sample_file or die $!;
while ( <$in_fh> ) {
s/hld_cf_id/1234/g; # replacing some content while writing
print {$out_fh} $_;
}
}
print {$out_fh} $footer;
close $out_fh or die $!;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…