Soop
Soop

Reputation: 407

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

I'm trying to write a configuration script. For each customer, it will ask for variables, and then write several text files.

But each text file needs to be used more than once, so it can't overwrite them. I'd prefer it read from each file, made the changes, and then saved them to $name.originalname.

Is this possible?

Upvotes: 3

Views: 1714

Answers (4)

carillonator
carillonator

Reputation: 4743

assuming you want to read in one file, make changes to it line-by-line, 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;

Upvotes: 0

brian d foy
brian d foy

Reputation: 132822

You want something like Template Toolkit. You let the templating engine open a template, fill in the placeholders, and save the result. You shouldn't have to do any of that magic yourself.

For very small jobs, I sometimes use Text::Template.

Upvotes: 4

Greg Bacon
Greg Bacon

Reputation: 139521

The code below expects to find a configuration template for each customer where, for example, Joe's template is joe.originaljoe and 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";
}

Upvotes: 0

ennuikiller
ennuikiller

Reputation: 46965

why not copy the file first and then edit the copied file

Upvotes: 1

Related Questions