in reply to In-place editing in a script

Is there any reason not to just use Config::IniFiles to do the editing as well as reading? From the docs it look like you want...

$cfg->setval ($host,$fn, $value);

Of course you need to handle loading and saving the file agian as well. As for why your code doesn't work, it looks like you open a single file and read from it. Try opening the file to read from, and the temp file to write to. Then copying the temp file over the old file after closeing them both.


___________
Eric Hodges

Replies are listed 'Best First'.
Re: Re: In-place editing in a script
by rjoost (Novice) on Nov 26, 2003 at 20:48 UTC
    That's a great idea! I just started using Config::IniFiles and haven't thought of using the setval fn. I'm working that now. It would still be cool to know how to do a substition within a range. It's great to $_ =~ s/$pattern1/$pattern2/ but to do something like $_ =~ m/BEGIN/ .. m/END/s$pattern1/$pattern2... Anyway, thanks for your help! Perl is getting more and more and more and more cool /Rob
      It's very simple to do search and replace with s/// on simple config files, without using any modules. And you don't need a temporary file either, just load the entire config file into memory, search and replace keys, and write it back to the config file. Perl is great at doing this kind of stuff.

      use strict; use Data::Dumper; my @config; { local $/ = '['; @config = <DATA>; } SetConfigKey(\@config, 'bdstest', 'Location', 'Somewhere'); SetConfigKey(\@config, 'bdstest', 'OS', 'WindowsXP'); SetConfigKey(\@config, 'custard', 'MainFunction', 'Perl Perl Perl'); SetConfigKey(\@config, 'custard', 'SCSI', 'YES'); print @config; sub SetConfigKey { my ($config, $section, $key, $value) = @_; foreach (@{$config}) { # loop through config sections next if ! /^$section\]/; # skip if unwanted s/\Q$key\E\s*=.*/$key=$value/; # replace the value } } __DATA__ [bdstest] MainFunction= SystemType=U5 Env= Location= Serial=FW0094810719 Hostid=80c0dc14 OS=Solaris Version=8 Disk=1x8 Memory=128 CPU=1x360 qfe= SCSI= GraphACC= SupportContract= #END [custard] MainFunction= SystemType=U5 Env= Location= Serial=FW00250126 Hostid=80c0aee2 OS=Solaris Version=8 Disk=1x8 Memory=256 CPU=1x360 qfe= SCSI= GraphACC= SupportContract= #END
      And the output is -
      [bdstest] MainFunction= SystemType=U5 Env= Location=Somewhere Serial=FW0094810719 Hostid=80c0dc14 OS=WindowsXP Version=8 Disk=1x8 Memory=128 CPU=1x360 qfe= SCSI= GraphACC= SupportContract= #END [custard] MainFunction=Perl Perl Perl SystemType=U5 Env= Location= Serial=FW00250126 Hostid=80c0aee2 OS=Solaris Version=8 Disk=1x8 Memory=256 CPU=1x360 qfe= SCSI=YES GraphACC= SupportContract= #END