使用Perl 6进行批处理文本处理

问题描述 投票:3回答:2

我正在阅读劳伦特罗森菲尔德的Think Perl 6,以及Allen B. Downey最近的阅读非常好。

它的.tex文件在github here中可用。

它有这样的代码示例:enter image description here

我认为让代码块像这样着色非常有用:enter image description here

为此,我们必须批量处理上面的存储库中包含的所有.tex文件。要做到这一点,我们必须转换乳胶代码:

\begin{verbatim}
        say 42 ==  42;           # True
        say 42 ==  42.0;         # True
        say 42 ===  42;          # True
        say 42 === 42.0;         # False
\end{verbatim}


\begin{verbatim}
$x eq $y            # $x is string-wise equal to $y
$x ne $y            # $x is string-wise not equal to $y
$x gt $y            # $x is greater than $y (alphabetically after)
$x lt $y            # $x is less than $y (alphabetically before)
$x ge $y            # $x is greater than or equal to $y
$x le $y            # $x is less than or equal to $y
$x eqv $y           # $x is truly equivalent to $y
\end{verbatim}

\begin{minted}{perl6}
        say 42 ==  42;           # True
        say 42 ==  42.0;         # True
        say 42 ===  42;          # True
        say 42 === 42.0;         # False
\end{minted}


\begin{minted}{perl6}
$x eq $y            # $x is string-wise equal to $y
$x ne $y            # $x is string-wise not equal to $y
$x gt $y            # $x is greater than $y (alphabetically after)
$x lt $y            # $x is less than $y (alphabetically before)
$x ge $y            # $x is greater than or equal to $y
$x le $y            # $x is less than or equal to $y
$x eqv $y           # $x is truly equivalent to $y
\end{minted}

我想用Perl 6实现这一目标。这就是我打算做的事情。

THIS IS DUMMY CODE

# First I want to skim all the .tex files in the cloned repo (with git) 

for dir("ThinkPerl6/book") ->$file {
  say $file if $file~~/\.tex/;
}

# Read each .tex file and modify, replace `\begin{verbatim}` with `\begin{minted}{perl6}`

for "$file.tex".IO.lines -> $line {
  substitute with "\begin{minted}{perl6}" if $line ~~/\\begin\{verbatim\}/;
}

# Read each .tex file and modify, replace `\end{verbatim}` with `\end{minted}`

for "$file.tex".IO.lines -> $line {
  substitute with "\end{minted}" if $line ~~/\\end\{verbatim\}/;
}

我无法超越这一点。有帮助吗?使用正则表达式会非常有帮助。

最好的祝福,

苏曼

regex latex perl6 rakudo
2个回答
4
投票

您需要执行以下步骤:

  • 创建应用了替换的每一行的副本。你可以使用subst method
  • 将修改后的副本写入新文件(可能添加扩展名为.new
  • 可选地,移动.new以覆盖原始文件。请参阅this example获取灵感。

我希望这有帮助。


1
投票

以下是moritz前两个要点的一个实现。

my $fh-out = open "$file.new.tex", :w; # Create a new file

# Print out next file, line by line
for "$file.tex".IO.lines -> $line is copy {

    # Make changes, if needed
    $line.subst-mutate('\begin\{verbatim\}','\begin{minted}{perl6}');
    $line.subst-mutate('\end\{verbatim\}','\end{minted}');

    # Print line
    $fh-out.put: $line;
}
© www.soinside.com 2019 - 2024. All rights reserved.