Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to detab (expand tabs) using Perl?

Tags:

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.

like image 651
Uri Avatar asked Nov 27 '22 00:11

Uri


1 Answers

What ever happened to the old Unix program "expand"? I used to use that all the time.

like image 136
Paul Tomblin Avatar answered Dec 19 '22 18:12

Paul Tomblin