我想在 HERE DOCUMENT 中嵌入 token ,然后使用 (s)printf
在最后一个字符串上用实际值替换这些标记。原因是:这使得构建 HERE DOCUMENT 变得更加容易,其中的某些部分是不同的。
解释一下,这是我在 Python 中将如何做到这一点的。从下面的小例子中,我会更清楚我想要做什么。在 Python r"""
类似于 Perl <<EOT
,即它构建多行原始字符串。字符串必须以 """
结尾类似于以 EOT
结尾的 Perl .
s=r"""
\documentclass[12pt,titlepage]{article}
\begin{document}
\title{%(title)s}
\date{%(date)s}
some text
\end{document}"""
print s % {"title": "My report","date": "1/1/2016"}
以上打印品
\documentclass[12pt,titlepage]{article}
\begin{document}
\title{My report}
\date{1/1/2016}
some text
\end{document}
注意
%(title)
和 %(date)
最后被给定的值替换。这与执行 sprintf('%s',some_string)
非常相似。 ,但在这里它应用于原始字符串本身。这非常方便,并且使构建原始字符串变得非常容易。这是 MWE在 Perl 中,但我被困在最后一部分,我也不知道如何做整个事情:
#!/usr/bin/perl -w
use strict;
use warnings;
my $title = "My report";
my $date = "1/1/2016";
my $s =<<'EOT';
\documentclass[12pt,titlepage]{article}
\begin{document}
\title{%(title)s}
\date{%(date)s}
some text
\end{document}
EOT
print($s); #how to format this in order to replace %title and %date
#emmbeded in $s with the values above? is it possible?
确保
EOT
最左边,后面没有空格。我不知道这在 Perl 中是否可行。但我认为如果在 Python 中是可能的,那么在 Perl 中也应该是可能的?
请注意,我不能在 HERE DOCUMENT 中使用插值,即
<<"EOT"
由于多种原因无法正常工作,并且必须使用非插值 HERE DOCUMENT。所以这样的事情对我不起作用:my $s =<<"EOT";
\documentclass[12pt,titlepage]{article}
\begin{document}
\title{$title}
\date{$date}
some text
\end{document}
EOT
最佳答案
你可能把事情复杂化了。是 Perl 有 sprintf
是的,您可以使用heredoc指定格式字符串,但是使用变量插值会容易得多:
#!/usr/bin/perl -w
use strict;
use warnings;
my $title = "My report";
my $date = "1/1/2016";
my $s =<<"EOT";
\documentclass[12pt,titlepage]{article}
\begin{document}
\title{$title}
\date{$date}
some text
\end{document}
EOT
print $s;
请注意,我在
EOT
周围更改了您的单引号。双引号。通常你可以在双引号字符串中包含一个变量名,例如:
"$title"
但如果您需要在后面加上文字字母、数字或下划线,则只需将花括号括在变量名周围:"${title}_word"
.要按要求回答问题,您可以执行以下操作:
#!/usr/bin/perl -w
use strict;
use warnings;
my $title = "My report";
my $date = "1/1/2016";
my $s =<<'EOT';
\documentclass[12pt,titlepage]{article}
\begin{document}
\title{%s}
\date{%s}
some text
\end{document}
EOT
printf($s, $title, $date);
Perl 的
sprintf
不支持命名占位符。编辑:正如@Nasser 在稍后的评论中指出的那样,我的第一个示例无法按书面方式工作,因为从单引号更改为双引号意味着反斜杠需要加倍,并且任何文字
$
字符串中的字符也需要转义。
关于perl - 是否可以应用 sprintf 来格式化 HERE DOCUMENT 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31015655/