user685275
user685275

Reputation: 2167

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.

Upvotes: 4

Views: 361

Answers (2)

rmmh
rmmh

Reputation: 7095

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.

Upvotes: 8

Marc B
Marc B

Reputation: 360762

The e flag on the regex means to treat the replacement string (' ' x (...etc...) as perl code and interpret/execute it for each match. So, basically look for any place there's 1 or more (+) tab characters (\t), then execute the small perl snippet to convert those tabs into spaces.

The snippet calculates how many tabs were matched, multiplies that number by 8 to get the number of spaces required, but also accounts for anything which may have come before the matched tabs.

Upvotes: 2

Related Questions