perl – 是否可以应用sprintf格式化HERE DOCUMENT字符串?
我想在这里的文档中嵌入令牌,然后在最后的字符串上使用printf来用实际值替换这些令牌.原因是:这使得构建HERE文档变得更加容易,其中一些部分是变化的.
为了解释,这是我将如何在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)非常相似,但这里它应用于原始字符串本身.这非常方便,可以很容易地构建原始字符串. 这是Perl中的一个MWE,但是我被困在最后一部分,我也不知道如何做到这一切: #!/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文档中使用插值,即<<“EOT”由于多种原因不起作用,并且必须使用非插值HERE文档.所以这样的事情对我不起作用: my $s =<<"EOT"; documentclass[12pt,titlepage]{article} begin{document} title{$title} date{$date} some text end{document} EOT 解决方法
要回答这个问题,有几个选择;我将只介绍两种更简单的实现方法(即printf / sprintf和regex).
> printf / sprintf 如果您知道占位符的顺序,则可以使用正确的模板化变量%s作为字符串,并使用printf调用中的变量插入值. #!/usr/bin/perl 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); >正则表达式 使用正则表达式,您可以查找文字字符串并将其替换为某个所需的值(变量). 简单替换 #!/usr/bin/perl 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 $s =~ s/$(title|date)/"$$1"/eeg; # ee is important and so is wrapping the replacement pattern in a string print $s; 哈希表替换 您可以通过使用替换哈希使该过程更加自动化/灵活.这有助于自动生成正则表达式模式并使用哈希表来检索替换的相应值.好处是你可以在哈希中添加更多或更少的变量,而不必再次触摸正则表达式(模式不会变得更大). #!/usr/bin/perl use strict; use warnings; my $replace = { title => q{My report},date => q{1/1/2016} }; my $s = <<'EOT'; documentclass[12pt,titlepage]{article} begin{document} title{$title} date{$date} some text end{document} EOT $s =~ s/$(@{[ join '|',keys %$replace ]})/$replace->{$1}/g; print $s; 正则表达的警告 然而,有许多警告.例如,自动换行可能是一个问题,具体取决于变量的中断位置 – 正则表达式未设置为查找.更值得关注的是,如果您确实希望文本字符串’$title’或’$date’出现在生成的文档中(执行TeX代码之后),则正则表达式会将其替换为某个值.您必须确定哪种方法最适合您. 通常,在模板/解析中没有单行答案,并且由于各种原因(例如,性能,可维护性,逻辑/复杂性,或者仅仅因为它不能以其他方式工作)它通常涉及多个语句处理. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |