) * 8 - length(...">

Extending tabs in perl

just ran into code to do tab extension in perl, here is the code:

1 while $string =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e; 

I tested it to work, but I'm too new to understand this, someone wants to explain a little why it works? or any pointer to related material that could help me figure this out would be helpful, thanks a lot.

+4
source share
2 answers

Perl allows you to embed arbitrary code as replacement expressions in regular expressions.

$& is the string matched by the last match of the pattern — in this case, a certain number of tab characters.

$` is the line that precedes what matches the last match of the pattern - this allows you to find out how long the previous text was, so you can choose the right rows in the columns.

For example, running this for the string "Something\t\t\tsomething else" , $& "\t\t\t" , and $` is "Something" . length($&) is 3, so no more than 24 spaces are required, but length($`)%8 is 1, so to make it column-aligned every eight, it adds 23 spaces.

+8
source

The e flag in the regular expression means processing the replacement string ( ' ' x (...etc... ) as Perl code and interpreting / executing for each match. So basically find any place there 1 or more ( + ) characters tabs ( \t ), then run a small piece of perl to convert these tabs to spaces.

The fragment calculates how many tablets were matched, multiplies this number by 8 to get the required number of spaces, but also takes into account everything that could occur before the matching tabs.

+2
source

All Articles