0

我正在使用 Perl 来实现这一点

while(<INFILE>){
        chomp;
         if(/\<td/){
          system("perl -i -e 's/<td/<td bgcolor="blue"/g' $_");
          }
}

当我运行命令时,我得到

./HtmlTest.pl file.html
Bareword found where operator expected at ./HtmlTest.pl line 13, near ""perl -i -e 's/<td/<td bgcolor="grey"
        (Missing operator before grey?)
String found where operator expected at ./HtmlTest.pl line 13, near "grey"/g' $_""
syntax error at ./HtmlTest.pl line 13, near ""perl -i -e 's/<td/<td bgcolor="grey"
Execution of ./HtmlTest.pl aborted due to compilation errors.

我不知道为什么

即使我运行为

perl HtmlTest.pl file.html

我得到同样的错误。

示例 html 表

 <td>ABC</td>
 <td>DEF</td>
 <td>20:00:00</td>

任何建议表示赞赏

4

3 回答 3

3

在解析复杂的 HTML 文件时,正则表达式可能会变得低效,更好的方法是使用专用的 HTML 解析器。这是一个使用XML::LibXML的示例,前提是您有一个有效的 HTML 文件:

use strict;
use warnings;
use XML::LibXML;

my $filename = 'file.html';
my $html = XML::LibXML->load_html( location  => $filename );
for my $node ($html->findnodes('//td')) {
    $node->setAttribute(bgcolor => "blue");
}
print $html->toStringHTML;
于 2020-09-04T19:14:51.893 回答
1

我认为您需要在字符串中转义,"因为它抱怨 "near "grey"/g' (假设您在代码中尝试使用灰色)

由于整个字符串是:"perl -i -e '<string_no_quotes>' $_"如果 string_no_quotes 有 " 它会给出这个错误,所以它需要被转义。

更新:

如果像这样的工作,您将其编写为标准输出并将其通过管道传输到文件中吗?:

foreach my $i ('<td>ABC</td>', '<td>DEF</td>', '<td>20:00:00</td>', '<h1>test</h1>') {
  chomp;
  
  $_ = $i;
  if (/\<td/) {
      print 's/<td/<td bgcolor="blue"/g';
   } else {
      print $_;
   }
}

我用 for 循环替换了 while 循环,这样我就可以在在线解析器中对其进行测试。我使用的是这个:https ://www.tutorialspoint.com/execute_perl_online.php

于 2020-09-04T18:24:13.183 回答
1

在 OPs 代码中,我们有以下行,应将其更正为下一个形式

system("perl -i -e 's/<td/<td bgcolor=\"blue\"/g' $_");

这是错误的,$_将保留从当前行读取<INFILE>但 perl 将期望输入文件。

以下代码演示了不使用任何模块的替代解决方案。这个解决方案也不是最好的。

use strict;
use warnings;

while( <DATA> ) {
    s/<td>/<td bgcolor="blue">/;
    print;
}

__DATA__

<block>
  Some text goes in this place
</block>

 <td>ABC</td>
 <td>DEF</td>
 <td>20:00:00</td>
 
 <p>
    New paragraph describing something
 </p>

而不是使用bgcolor="blue"更正确的方法是外部 CSS 样式style='some_style'

这种方法将允许在不接触 html 文件的情况下更改所需标签的样式文件。

您使用所需的样式编辑 CSS 样式文件,神奇地您的网页将显示新的颜色/文本样式/列表/类型等。

HTML 样式 CSS

于 2020-09-05T03:12:19.597 回答