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; }
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |