in reply to Re: In-place editing in a script
in thread In-place editing in a script

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

Replies are listed 'Best First'.
Re: Re: Re: In-place editing in a script
by Roger (Parson) on Nov 27, 2003 at 00:19 UTC
    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