victorz22 has asked for the wisdom of the Perl Monks concerning the following question:
Hello Monks, I am trying to read in a file, search for a hash, replace all the text within two hash keys, and then write the changed data back into the file. I wrote a function called truncateText() to that uses the hash keys as the key words for the beginning and end of the block I need. My function to parse text between two keywords works but I am having difficulty replacing the data in the file. I haven't written the code yet to write back into the file because the data wasn't getting replaced accurately. Thank you so much monks for your endless wisdom.
sub populateHash{ my $inputFile = 'input.txt'; my $fileContent = do { open(my $fileHandle, $inputFile ) or die "Could not open file +'$inputFile ' $!"; local $/; <$fileHandle>; }; my $hashData = truncateText($fileContent, "key1 => {", "key2 =>"); my $dataToReplace = truncateText($hashData, "END_SEARCH_PATHS", "E +ND_SEARCH_PATHS"); #Removes Comments works best if called multiple times $dataToReplace =~ s/\#.*//; $dataToReplace =~ s/\#.*//; $dataToReplace =~ s/\#.*//; $dataToReplace =~ s/\#.*//; #replacementData was gathered in another function and stored i +n a global variable $fileContent =~ s/$dataToReplace/$replacementData/g; print Dumper($fileContent); } sub truncateText{ #Truncates text by removing everything before and and after the pa +ssed in variables my($text, $beginString, $endString) = @_; my $truncatedText; if($text =~ /\Q$beginString\E(.*?)\Q$endString\E/s){ $truncatedText = $1; #print $truncatedText; } return $truncatedText; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Replacing a block of text inside two keys with another block of text
by GrandFather (Saint) on Apr 24, 2017 at 21:32 UTC | |
by victorz22 (Sexton) on Apr 24, 2017 at 22:03 UTC | |
by LanX (Saint) on Apr 24, 2017 at 22:41 UTC | |
by Anonymous Monk on Apr 25, 2017 at 02:02 UTC | |
|
Re: Replacing a block of text inside two keys with another block of text
by huck (Prior) on Apr 24, 2017 at 22:51 UTC | |
|
Re: Replacing a block of text inside two keys with another block of text
by LanX (Saint) on Apr 24, 2017 at 22:51 UTC | |
by victorz22 (Sexton) on Apr 24, 2017 at 23:31 UTC |