'

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

为什么要应用perl代码

 undef $/;  # read in entire file or STDIN
 $_ = <>;
 s|<head>.*<\head>|<head>...</head>|s;

应用于包含的文本文件

 <head>[anything]</head>

生产

 ...

并不是

 <head>...</head>

?

当替换REPLACE字段中的'<'字符被省略时,如

 s|<head>.*</head>|head>.../head>|s;

替代产生

 head>...end>

'<'字符有所不同,但我找不到原因的解释。

如何在替换结果中产生'<'?

perl substitution
2个回答
1
投票

第一个代码段不会产生您声称的输出。

$ perl -e'$_ = "<head>foo</head>"; s|<head>.*<\head>|<head>...</head>|s; CORE::say'
<head>foo</head>

它不执行替换的原因是因为\h匹配水平空白字符。

你可能想用</head>而不是<\head>。这产生了所需的输出。

$ perl -e'$_ = "<head>foo</head>"; s|<head>.*</head>|<head>...</head>|s; CORE::say'
<head>...</head>

没有什么比你的代码更像是你声称的...。当然,如果您在HTML查看器中查看包含<head>...</head>的文件,它将显示为...。要生成呈现为<head>...</head>的HTML,您需要执行一些转义。

$ perl -e'
   use HTML::Escape qw( escape_html );
   $_ = "<head>foo</head>";
   s|<head>.*</head>|<head>...</head>|s;
   CORE::say(escape_html($_));
'
&lt;head&gt;...&lt;/head&gt;

0
投票

假设<\head>是一个错误,你的代码就会达到预期的效果。无论您使用什么来查看结果,都可能是您丢失标签的原因。您是否在浏览器中查看输出?

当您删除开头的<时,标签不再像标签那样显示而不是被操作。

© www.soinside.com 2019 - 2024. All rights reserved.