in reply to Re^3: Search replace with a block
in thread Search replace with a block

Based on both the feedback I did the following -
#!/usr/bin/perl -w use strict; my $location ="/newlocation"; my $file_name ='ipconn.conf'; $/ = undef; open (FILE, "< $file_name") or die $!; my $file = <FILE>; close FILE; my $value; # check for the block we want if ($file =~ m/\<Location\ $location.+?\<\/Location\>/s){ my $block = $&; if($block =~ s/MaxConnPerIP\s*(.+?)*/MaxConnPerIP 10/g) { print $block; } }
Now the issue I have is $block has the updated text and $file has the entire file. How do I merge those , by merge meaning either remove the matching block and add this new one. Or change my value into the original variable which has the file. Which is part of the reason I was leaning on using tie::file, updating the file was so much more easier. Let me know what you guys think. Thank you for your help.

Replies are listed 'Best First'.
Re^5: Search replace with a block
by beech (Parson) on May 12, 2016 at 06:31 UTC

    Maybe use ReformulateLocation to perform the location based substitution?

    :D

      Thank you Beech, will play around with the code you pasted as well. For now I managed to get it to work using the following -
      #!/usr/bin/perl -w use strict; #my $location ="/location2.html"; my $location ="/"; my $file_name ='pconn.conf'; my $conf_new ; my $max_connections=10; $/ = undef; #Open file for reading and slurp into file open (FILE, "< $file_name") or die $!; my $file = <FILE>; close FILE; # check for the block we want if ($file =~ m/\<Location\ $location.+?\<\/Location\>/s){ my $first=$`; #Everything before matched string my $block = $&; #Matched block my $second=$'; #Everything after matched string if($block =~ s/MaxConnPerIP\s*(.+?)*/MaxConnPerIP $max_connections +/g) { $conf_new= $first . $block . $second; } } # Open file for writing and dump matched and unmatched block open (OUTFILE, "> $file_name.tmp") or die "cannot open $file_name.tmp +for write $!"; print OUTFILE $conf_new; close OUTFILE; # save copy of original file rename ($file_name,"$file_name.bak") || die "problem with rename $!"; # replace original with the modified version rename ("$file_name.tmp", $file_name) || die "problem with rename $!";