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

I wanted to separate the source files. (Please do not flame about WHY I would like to turn off my sources. This is not the main thing :-) I could not find usefulness for this. Eclipse did not do this for me, so I implemented my own.

I could not put it in one liner (-e) program. I came with the following, which worked great.

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, this makes me wonder if Perl, the champion word processing language, is the right tool. The code does not seem very elegant. If I had to select a source assuming tab = 8 spaces, the code would look even worse.

In particular, because I can think of a deterministic state machine with 4 states to do the job.

I have the feeling that there is a more elegant solution. Am I missing the Perl idiom? In the spirit of TIMTOWTDI, I am interested in other ways to do this.

and.

+4
source share
7 answers

I remember a detabify script from one of O'Reilly books, but now I can not find the link.

I also had to solve this problem, and I settled on this brief solution for defining a string:

 1 while $line =~ s/\t/" " x ($tablength - ($-[0] % $tablength))/e ; 

In this regular expression, $-[0] is the length of the β€œpre-matched” part of the string β€” the number of characters before the tab character.


As single line:

 perl -pe '1 while s/\t/" "x(4-($-[0]%4))/e' input 
+7
source

What happened to the old Unix "expand" program? I used it all the time.

+12
source

When I want to expand tabs, I use Text :: Tabs .

+7
source

This is easy to do in vim:

 :set expandtab :retab 

http://vim.wikia.com/wiki/Converting_tabs_to_spaces

+5
source

You must not be here vi . Emacs:

 Mx tabify Mx untabify 
+3
source

I do this in vim with:

 :%s/^V^I/ /g 

(This is the literal ^ V followed by the letter tab ) and then :%gq to fix the wrong interval. Perl is redundant.

+2
source

Exact expression:

 1 while $line =~ s/\t/" " x ($tablength+1 - ($-[0] % $tablength))/e ; 

And the extension is useful for the command line not inside the program, which may expand or not create some lines.

+1
source

Source: https://habr.com/ru/post/1311546/


All Articles