Re: Problem with replacing string in file




boyd wrote:
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;

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;
}

.



Relevant Pages

  • Re: Problem with replacing string in file
    ... boyd wrote: ... perlpra@xxxxxxxxx (Perl Pra) wrote: ... chomp $line; # get rid of eol stuff ... open my $LOGFILE, '<', $file; ...
    (perl.beginners)
  • Re: Redirection
    ... and Its Expensive to Die: Dont Do It for FREE!!! ... Install hijackthis on your C: ... Open the program and click on Do a system scan and save a logfile. ...
    (microsoft.public.windows.inetexplorer.ie6.browser)