victorz22 has asked for the wisdom of the Perl Monks concerning the following question:
Hello Monks, I am trying to replace text in a file and write it to a copy of that file but i get an error where the only some of the text gets replaced and the rest is just added on to the beginning of the file(I don't want it there). Please let me know if you have any questions, and Thank You!
the data that needs to be replaced is just a bunch of paths to certain + directories and it looks kinda like this #data to replace old/path/to/some/file another/old/path/to/some/file one/more/old/path/to/some/file #desired replacement new/path/to/some/file another/new/path/to/some/file one/more/new/path/to/some/file
#Code to read in file my $inputFile = 'file.txt'; my $fileContent = do { open(my $fileHandle, $inputFile ) or die "Could not open file +'$inputFile' $!"; local $/; <$fileHandle>; }; #replace search paths with data in hash per key, $oldSearchPat +hs and %searchPaths are initialized elsewhere foreach my $key (keys %searchPaths){ $fileContent =~ s/\Q$oldSearchPaths\E/\n$searchPaths{$key}/; } #code to write to file my $filename = 'fileCopy.txt'; open(my $fh, '>', $filename) or die "Could not open file '$filenam +e' $!"; print $fh $fileContent; close $fh; print "Writing to File Done! \n";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Writing to a file
by kcott (Archbishop) on May 06, 2017 at 05:33 UTC | |
|
Re: Writing to a file
by shmem (Chancellor) on May 06, 2017 at 06:43 UTC | |
|
Re: Writing to a file
by GotToBTru (Prior) on May 05, 2017 at 20:57 UTC | |
|
Re: Writing to a file
by marinersk (Priest) on May 06, 2017 at 13:41 UTC | |
|
Re: Writing to a file
by Anonymous Monk on May 05, 2017 at 20:29 UTC | |
by victorz22 (Sexton) on May 05, 2017 at 20:37 UTC | |
by AnomalousMonk (Archbishop) on May 05, 2017 at 22:21 UTC | |
by Laurent_R (Canon) on May 05, 2017 at 21:09 UTC | |
by victorz22 (Sexton) on May 05, 2017 at 21:44 UTC |