Re: Problem with replacing string in file



In article <tbmoore9-CAC060.08374625112006@xxxxxxxxxxxxxxxx>,
boyd <tbmoore9@xxxxxxxxxxx> wrote:

In article
<8070ef410611250440h77c537c0k8c5d36e5fa10fcab@xxxxxxxxxxxxxx>,
perlpra@xxxxxxxxx (Perl Pra) wrote:
...

Here's my version (not completely - I tried to retain as much of yours
as I could :) ) It is longer than it has to be, but it is easier to
follow without shortcuts.

Boyd

#!/usr/bin/perl
use strict;
use warnings;
use Carp;
$|++;

my $config_path = "conf.txt";
my $file = "log.txt";
my %config_hash = ();
open FH, "$config_path";
while ( my $line = <FH> ) {
chomp $line; # get rid of eol stuff
my ( $key, $val ) = $line =~ /^(\w+)=(.+)$/mg;
$config_hash{$key} = $val;
}
close FH;

open my $LOGFILE, '<', $file;
my @log_lines = <$LOGFILE>; #slurp in the file - good for small files
close $LOGFILE;
my $changed = 0; # flag to see if we change the array
for my $line (@log_lines) {
chomp $line;
my ( $key, $val ) = $line =~ /^(\w+)=(.+)$/mg;
if ( exists $config_hash{$key} ) {
$line = "$key=$config_hash{$key}";
$changed++; # yes, we changed it.
}
}

if ($changed) {
#0 == system("copy $file $file.bak") # the MS-DOS version (I think)
0 == system("cp $file $file.bak") # the unix version
or die "Could not make backup of $file\n";
open $LOGFILE, '>', $file;
for my $line (@log_lines) {
print $LOGFILE "$line\n";
}
close $LOGFILE;
}
.