in reply to Search for a BLOCK of text and selectively replace

This code will parse the whole file into a hash. Then you can manipulate it via the supplied subroutines (add_keyword, del_keyword, get_keyword). You can find examples to their usages to the end of the code.

#!/usr/bin/perl -w use strict; use Data::Dumper; sub read_config { my $file = shift; # Slurp in the file open (RUNSET, "<$file") or die "Can't access '$file': $!"; my %conf; my $handle; while (<RUNSET>) { chomp; next if $_ eq '' or /^;/; if (/^\*(.*)$/) { if ($1 eq 'END') { undef($handle); } else { $handle = $1; %{$conf{$handle}} = (); } next; } if ($handle) { my($var, $value) = split('\s*=\s*', $_, 2); next unless defined $var; $conf{$handle}{$var} = $value; } } close RUNSET; return \%conf; } sub check_params { my ($config, $block, $keyword, $value) = @_; return unless ref($config) eq 'HASH'; return unless defined($block); return unless ref($config->{$block}) eq 'HASH'; return unless defined($keyword); return @_; } sub add_keyword { my ($config, $block, $keyword, $value) = check_params(@_); return unless defined($config); if (defined(${$config->{$block}}{$keyword})) { print "Replacing value of $keyword in $block (previously " . ${$config->{$block}}{$keyword} . ").\n"; } else { print "Adding the new $keyword keyword to $block block.\n"; } ${$config->{$block}}{$keyword} = $value; } sub del_keyword { my ($config, $block, $keyword) = check_params(@_); return unless defined($config); if (defined(${$config->{$block}}{$keyword})) { print "Deleting $keyword from $block.\n"; return delete(${$config->{$block}}{$keyword}); } else { print "Tried to delete a nonexistant key $keyword in $block block. +\n"; } } sub get_keyword { my ($config, $block, $keyword) = check_params(@_); return unless defined($config); if (defined(${$config->{$block}}{$keyword})) { return ${$config->{$block}}{$keyword}; } else { print "Tried to access a nonexistant key $keyword in $block block. +\n"; } } my $config = read_config('test.txt'); add_keyword($config, 'DESCRIPTION', 'test', 10); add_keyword($config, 'DESCRIPTION', 'keyword', 'aa'); del_keyword($config, 'DESCRIPTION', 'keyword2'); del_keyword($config, 'DESCRIPTION', 'keyword3'); print Dumper($config); exit;

I hope this helps.

--
Alper Ersoy