in reply to Re: Editing a Config file
in thread Editing a Config file

This node falls below the community's threshold of quality. You may see it by logging in.

Replies are listed 'Best First'.
Re^3: Editing a Config file
by dHarry (Abbot) on Mar 05, 2010 at 14:51 UTC

    Please use <code> code goes here</code> tags, it improves readability a lot;)

    Your not far away, lets take a fresh look and decompose the problem, for example like:

    1. reading of a config file
    2. reading of user input
    3. writing/updating of the config file

    As a general comment put use strict; use warnings; in your scripts.

    1. Let's start with the reading of the file first.

    #!/usr/bin/perl use strict; use warnings; my %config; my $filename = "TestConfig.cfg"; open ( FILE,'<', $filename) or die "Cannot open file: $!"; while (<FILE>) { chomp; s/#.*//; # no comments s/^\s+//; # no leading white s/\s+$//; # no trailing white next unless length; # anything left? my ($var, $value) = split(/\s*=\s*/, $_, 2); $config{$var} = $value; } close FILE; while(my ($key, $value) = each(%config)) { print "key: $key, value: $value\n"; }

    I used the following config file:

    ServerIP=<10.11.200.189> FirewallIP=<10.11.200.189> WebServerListenPort=<5566> ConnectionStartPort=<9400> ConnectionEndPort=<9419> RecordServerIP=<10.11.200.189> MediaPort=<7080> ControlPort=<7081>

    Make sure you understand what happens. Why is the 2 used in the split function?

    2. Reading of user input

    You are on the right way. There are more ways to do it, I would probably use a module from CPAN, but using STDIN should work fine.

    3. Writing of the config file

    You open the file for * reading * only:) You can work with a temporary file and later overwrite the original or do the update in-place.

    HTH

    Cheers

    Harry