views:

129

answers:

4

Hello! 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?

+1  A: 

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

ennuikiller
Ah ok, I'll give that a go :) Seems obvious, but I'm a noob
Soop
A: 

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";
}
Greg Bacon
I've figured something out: I forgot that perl doesn't ... "flow" like other scripts.I stuck a $customer_name = "placeholder";in there, and got a file called CPE_Option_A.txt.placeholder.So I think the problem is that I have to make sure it copies the file last.
Soop
A: 

This is what I have so far:

#!/usr/bin/perl
use File::Copy;
        print "Enter the customer Index";
        $index = <STDIN>;
        chop $index;
        if (!$index) { print "You need to type something!\n"; }

        print "Enter the customer name with spaces replaced with underscores and suffixed with the Index number, eg. o_learys-1";
        $customer_name = <STDIN>;
        chop $customer_name;
        if (!$customer_name) { print "You need to type something!\n"; }

$file = "CPE_Option_A.txt";
$newfile = $file . $customername;
#mkdir "$customer_name", 0777 unless -d "$customer_name";
copy ($file, $newfile) or die "you got the code wrong"

But it's not working. It seems to try copying the original and the new file. Which makes me think that I'm getting the concatenation wrong, but I can't see how!

Soop
You should really edit the question with these updates.
daotoad
Also, `use strict;`, `use warnings;`. Don't use `chop`, use `chomp` instead, add `$!` to your error message output to get the system error message.
daotoad
Ok, I'll try that stuff, sorry
Soop
+3  A: 

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.

brian d foy