Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tab expansion in perl

just encountered the code for doing tab expansion in perl, here is the code:

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

I tested it to be working, but I am too much a rookie to understand this, anyone care to explain a bit about why it works? or any pointer for related material that could help me understand this would be appreciated, Thanks a lot.

like image 287
user685275 Avatar asked Dec 27 '22 21:12

user685275


1 Answers

Perl lets you embed arbitrary code as replacement expressions in regexes.

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

$` is the string preceding whatever was matched by the last pattern match—this lets you know how long the previous text was, so you can align things to columns properly.

For example, running this against the string "Something\t\t\tsomething else", $& is "\t\t\t", and $` is "Something". length($&) is 3, so there are at most 24 spaces needed, but length($`)%8 is 1, so to make it align to columns every eight it adds 23 spaces.

like image 122
rmmh Avatar answered Jan 12 '23 00:01

rmmh