Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: How to replace Tab with spaces not altering postion

by bart (Canon)
on Oct 09, 2002 at 15:40 UTC ( #203966=note: print w/replies, xml ) Need Help??


in reply to How to replace Tab with spaces not altering postion

(Reinventing wheels can be fun, if the solution isn't too obvious. Perhaps you shouldn't be using this for real work, but OTOH, it's a bit like solving a crossword puzzle.)

I assume you want a tabstop per 8 characters? This appears to work, replacing each tab with a string of 1 to 8 spaces:

while(s/\t/" " x (8 - $-[0]%8)/e) {}
For example, in "a\tb", at the time of the replacement, $-[0] will be 1, so 7 spaces will be inserted, replacing the tab.

Note that s///g won't do the right thing, because it doesn't take into account the length of what's on the left of the match after any previous replacements; instead it'll continue to use the old length, as if nothing had been replaced yet. Thus, for the second match in "\t\t", $-[0] will still be 1, the length of the first "\t", and not 8, for the string of spaces that (already) replaced it.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://203966]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (9)
As of 2017-12-18 08:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What programming language do you hate the most?




















    Results (473 votes). Check out past polls.

    Notices?