Is there a better way to detab (expand tabs) using Perl?
Posted
by Uri
on Stack Overflow
See other posts from Stack Overflow
or by Uri
Published on 2010-06-01T19:27:16Z
Indexed on
2010/06/01
20:13 UTC
Read the original article
Hit count: 147
perl
I wanted to detab my source files. (Please, no flame about WHY I wanted to detab my sources. That's not the point :-) I couldn't find a utility to do that. Eclipse didn't do it for me, so I implemented my own.
I couldn't fit it into a one liner (-e) program. I came with the following, which did the job just fine.
while( <> )
{
while( /\t/ ) {
s/^(([^\t]{4})*)\t/$1 /;
s/^((([^\t]{4})*)[^\t]{1})\t/$1 /;
s/^((([^\t]{4})*)[^\t]{2})\t/$1 /;
s/^((([^\t]{4})*)[^\t]{3})\t/$1 /;
}
print;
}
However, it makes me wonder if Perl - the champion language of processing text - is the right tool. The code doesn't seem very elegant. If I had to detab source that assume tab=8 spaces, the code would look even worse.
Specifically because I can think of a deterministic state machine with only 4 states to do the job.
I have a feeling that a more elegant solution exists. Am I missing a Perl idiom? In the spirit of TIMTOWTDI I'm curious about the other ways to do it.
u.
© Stack Overflow or respective owner