Pathologically Eclectic Rubbish Lister | |
PerlMonks |
Re^5: Perl code to format the text file by inserting tag in blank lineby AnomalousMonk (Archbishop) |
on Feb 12, 2020 at 22:26 UTC ( [id://11112897]=note: print w/replies, xml ) | Need Help?? |
Would you mind explaining the 3 lines of code that you have replied me with? Note: In addition to the regex doc perlre linked by GrandFather, I would also recommend the excellent perlretut tutorial and the perlrequick quick reference. As mentioned before, in your posted code you seem to be trying to fix up some data after you've written it to a file. This is possible, but very tricky; the time to fix your data is before output. perl -i -lpe "s/^\s*$/<r><\/r>/g" some_file_name does the trick from the command line, but what is it really doing and how can you incorporate it in your Perl code? Deparsing can be helpful; see the O and B::Deparse core modules: This is the internal code generated and executed with the -i -l -p command-line switches (see perlrun). The workhorse s/// has been enclosed in a loop. The s[^\s*$][<r></r>]g expression operates by default on the $_ default scalar (see perlop and perlvar), which you can see being assigned values, successive records/lines from a file, in the while-loop condition expression in the deparsed code. (Note that the /g substitution modifier is not needed here (although it does no harm): the entire line is being replaced and this can only be done once.)
But you want to fix up the data before output. The first step is to generate the data:
The $out =~ s{ \A \s* \z }{<r></r>\n}xms; fixup statement could have been written in other, perhaps better ways. For instance: which could be considered self-documenting and moreover allows easy global alteration of the meanings of BLANK_LINE and EMPTY_R_PAIR. (This is an example of the Don't Repeat Yourself (DRY) or "define in one place" principle.) And that's all there is to it. It's a Simple Matter of Programming. :) Give a man a fish: <%-{-{-{-<
In Section
Seekers of Perl Wisdom
|
|