Perl 中的制表符扩展

发布于 2024-11-04 16:09:58 字数 327 浏览 6 评论 0原文

刚刚遇到执行 制表符扩展 ,这里是代码:

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

我测试了它的工作原理,但我是一个菜鸟,无法理解这一点,有人愿意解释一下它为什么工作吗?或任何可以帮助我理解这一点的相关材料的指针将不胜感激,非常感谢。

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

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

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

) % 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

寄居人 2024-11-11 16:09:58

Perl 允许您在正则表达式中嵌入任意代码作为替换表达式。

$& 是最后一个模式匹配所匹配的字符串,在本例中是一定数量的制表符。

$` 是最后一个模式匹配所匹配的内容之前的字符串,这可以让您知道前一个文本的长度,以便您可以正确地将内容与列对齐。

例如,针对字符串 "Something\t\t\tsomething else" 运行此命令,$&"\t\t\t"代码>,而<代码>$`是<代码>“某事”。 length($&) 为 3,因此最多需要 24 个空格,但 length($`)%8 为 1,因此要使其与列对齐每八个就增加 23 个空格。

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.

与往事干杯 2024-11-11 16:09:58

正则表达式上的 e 标志意味着将替换字符串 (' ' x (...etc...) 视为 Perl 代码,并为每个匹配解释/执行它因此,基本上查找有 1 个或多个 (+) 制表符 (\t) 的位置,然后执行小 perl 代码片段将这些制表符转换为空格

。 snippet 计算匹配的制表符数量,将该数字乘以 8 以获得所需的空格数,但也会考虑匹配制表符之前可能出现的任何内容。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文