P is for Practical | |
PerlMonks |
Re: How to replace \t with \sby Don Coyote (Hermit) |
on Jan 20, 2021 at 15:56 UTC ( [id://11127152]=note: print w/replies, xml ) | Need Help?? |
tr replaces a list of characters with another list of characters, so without modifiers this will not do as you think, it will only replace \t with the first incident of the replacement list.
Use the substitution operator s///. This will replace a match with a replacement string.
Or globally on the line.
Splitting on a repeated character singularly will produce multiple empty lists, that once replaced will essentially reconstruct the line as it was processed. Which is fine if that is what you want.
This can be seen more easily joining with a linefeed character\n.
Also note, join uses a literal string as a first argument. So you are not able to use a match escape for general whitespace to replace a literal character escape for a particular whitespace character. \t is a tab whitespace escape, that interpolates in double-quoted context. \s is a matching character escape that matches against any whitespace literal. \s would not interpolate inside double-quoted context as how would perl know to which whitespace literal you wanted to replace with? Whereas split also has the option to use the match m// operator in place of a literal string as its first argument. Moreover, literal ' ' space string to split alters splits behaviour in regard to white space parsing. Your goal is not clear about if that is your attempt to solve the problem or if that is something you are preparing the document for so that you can then perform. As such, depending on what it is you want to do you may be able to make use of a capturing split, or splitting directly on the tabs instead of spaces on the first pass.
And splitting on only incidents of only two or more consecutive characters.
This also has the advantage of not actually mangling your documents in place. There could be loose tab characters anywhere in all those files, so set up some small test lines to ensure the operator behaves a expected, and make backups. As per usual. edit: Clarified splits usage of string or match operator as first argument, and that \s does not interpolate. Dooon Coooyoooteee
In Section
Seekers of Perl Wisdom
|
|