Re: Problem with replacing string in file
- From: boyd <tbmoore9@xxxxxxxxxxx>
- Date: Sat, 25 Nov 2006 14:20:30 GMT
In article <tbmoore9-CAC060.08374625112006@xxxxxxxxxxxxxxxx>,
boyd <tbmoore9@xxxxxxxxxxx> wrote:
In articleHere's my version (not completely - I tried to retain as much of yours
<8070ef410611250440h77c537c0k8c5d36e5fa10fcab@xxxxxxxxxxxxxx>,
perlpra@xxxxxxxxx (Perl Pra) wrote:
...
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;
}
.
- Follow-Ups:
- Re: Problem with replacing string in file
- From: nobull67@xxxxxxxxx
- Re: Problem with replacing string in file
- References:
- Problem with replacing string in file
- From: Perl Pra
- Re: Problem with replacing string in file
- From: boyd
- Problem with replacing string in file
- Prev by Date: Re: perl string substitution
- Next by Date: Re: Problem with replacing string in file
- Previous by thread: Re: Problem with replacing string in file
- Next by thread: Re: Problem with replacing string in file
- Index(es):