Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks , I have this problem that I need your help with : I am reading a config file that contain the following :
[version] 2004 [type] update [scripts] scripts_file1 scripts_file2 inside my scripts_file# , I have something like this : #scripts_file1 #DO update ./script1 ./script2 in the other script I have #scripts_file2 #Do delete ./script21
what I am trying to do is read the config file and find out the type which is "update" in this case .Then read the scripts section and findout which file contain the update type , in this case it is scripts_file1. So my script that is reading the config file will only run scripts_file1 and not scripts_file2. I hope this is clear , if not I can try to clear it more . thanks for the help.

Replies are listed 'Best First'.
Re: reading & searching file
by ViceRaid (Chaplain) on Feb 16, 2004 at 17:55 UTC

    Hi

    First up, you might find it quicker to use a standard Config file format, like Config::IniFiles, XML::Config or maybe YAML. Then you'll save yourself having to write your own config reader.

    You don't say anything about what you've tried already, or what you're stuck on. You don't say much about what, generally you're trying to achieve. Trusting that this isn't homework, and taking it step by step, first you need to parse your main config file. Try reading it line by line, and noting when you find a new "block" starting:

    open(CONF, '<conf-main.txt') or die "Can't open file: $!"; my ( %config, $setting ); while ( my $line = <CONF> ) { chomp $line; # skip blank lines next if $line =~ /^\s*$/; # find named sections if ( $line =~ /^\[(\w+)\]/ ) { $setting = $1; next; } # save values if ( exists $config{$setting} ) { # squash into an array if already set $config{$setting} = ref($config{$setting}) ? [ @{ $config{$setting} }, $line ] : [ $config{$setting}, $line ]; } else { $config{$setting} = $line; } }

    Data::Dumper is very useful for checking that you've got what you expected in a variable after something like this:

    use Data::Dumper; print Data::Dumper::Dumper \%config;

    Then you need to check each of the script files to see if it's got the 'update' action. Again, you want to specify what you're looking for, and then reading each file line-by-line to see if it contains it.

    my $type_match = qr/#DO\s+$config{'type'}/i; foreach my $script_file ( @{ $config{'scripts'} } ) { open(SCRIPT_FILE, $script_file) or die "Can't open script file '$_': $!"; while ( my $line = <SCRIPT_FILE> ) { if ( $line =~ $type_match ) { print "File '$script_file' is the right type"; break; } } }

    Hope this helps
    ViceRaid