|Pathologically Eclectic Rubbish Lister
Immediately writing the results of search-and-replaceby Anonymous Monk
|on Aug 05, 2022 at 17:56 UTC
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
Most gracious monks: I am a Perl novice working on a script that takes a CSV file as input, uses the first element of each row as a string to search on, and the second element of each row as the replacement string. In the event that one search term appears in multiple rows, these are merged together so that the second element becomes an array of replacement candidates, reduced down to unique items. In either case, the user is prompted to adjudicate the replacement (either yes/no for a single replacement candidate, or a numeric input for multiple). I have the core functionality working, but some problems crop up when doing replacements on search strings for which other search strings are substrings.
For example, if my script finds that a file contains the search string 'IP whitelist' on a given line, even if I confirm that I want to replace this with 'IP access list', it will then prompt me to replace just 'whitelist' with one of its various candidates. What I would expect to happen in that case is that the replacement of 'IP whitelist' with 'IP access list' happens before the search for the 'whitelist' key is initiated, preventing it from finding a match there. Doing some digging, it seemed that setting up autoflushing would solve my problem, but either I've misunderstood and that is not a solution to the situation, or I have implemented it incorrectly. Here is the subroutine that performs the actual search-and-replace:
1) I was under the impression that autoflushing on the currently open filehandle can be set using the $| variable, but if that's the case, why doesn't this have any affect?
2) Is refactoring this subroutine so that it loops over the rows of the tables first, and then over each file in the inner loop a better solution? It seems like a lot more IO to be opening and closing every file over and over for each term, but I'm not a real programmer by any stretch, so I could be way off the mark here.
3) I also tried putting the line $target_file->flush; as the last line of each of the replacement 'if' statements, and that did nothing either.
Please let me know if there is any additional info I can provide that would help. Thank you very much.