Re: Problem with replacing string in file
- From: "nobull67@xxxxxxxxx" <nobull67@xxxxxxxxx>
- Date: 25 Nov 2006 07:15:51 -0800
boyd wrote:
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;
You don't actually use Carp so why use Carp?
$|++;
You never write anything to STDOUT so what is the point putting it into
autoflush mode?
my $config_path = "conf.txt";
my $file = "log.txt";
my %config_hash = ();
The explicit initializaion is noise, newly declared hashes start out
empty.
open FH, "$config_path";
You forgot "or die $!".
while ( my $line = <FH> ) {
chomp $line; # get rid of eol stuff
my ( $key, $val ) = $line =~ /^(\w+)=(.+)$/mg;
Remove the /mg it is just noise. As is the $ for that matter.
Always check success. If you want to assume the match always succedes
then just append "or die".
$config_hash{$key} = $val;
}
close FH;
open my $LOGFILE, '<', $file;
You forgot "or die $!".
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
Since it's just a boolean, undef will do just fine as "false" - no need
to set it to 0.
for my $line (@log_lines) {
chomp $line;
my ( $key, $val ) = $line =~ /^(\w+)=(.+)$/mg;
Again the /mg is just noise.
if ( exists $config_hash{$key} ) {
Again you should check the match succeded. Just checking defined($key)
would do.
$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";
Probably better to rename rather than copy. Which means you can use the
Perl bultin rename().
open $LOGFILE, '>', $file;
You forgot "or die $!".
for my $line (@log_lines) {
print $LOGFILE "$line\n";
}
close $LOGFILE;
}
.
- Follow-Ups:
- Re: Problem with replacing string in file
- From: boyd
- 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
- Re: Problem with replacing string in file
- From: boyd
- Problem with replacing string in file
- Prev by Date: Re: Problem with replacing string in file
- Next by Date: Re: perl string substitution
- Previous by thread: Re: Problem with replacing string in file
- Next by thread: Re: Problem with replacing string in file
- Index(es):
Relevant Pages
|