Perl: opening a file and saving it under a different name after editing

I am trying to write a configuration script. For each client, it will request variables, and then write several text files.

But each text file needs to be used several times, so it cannot overwrite them. I would prefer it to read from each file, make changes and then save them in $ name.originalname.

Is it possible?

+3
source share
4 answers

You want something like the Template Toolkit . You let the template open the template, fill in the placeholders, and save the result. You do not have to do any magic yourself.

Text:: Template.

+4

,

+1

In the code below it is supposed to find a configuration template for each client, where, for example, the Joe template joe.originaljoeand writes the output to 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";
}
0
source

provided that you want to read in one file, make changes to it in turn, and then write to another file:

#!/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;
0
source

Source: https://habr.com/ru/post/1728606/


All Articles