稀疏文档指出:
对于不想使用外部样式表的情况,您可以提供颜色作为哈希引用,其中键是 CSS 类(通常与令牌名称匹配),值是颜色。
PPI::HTML::CodeFolder的 POD有一个您可以使用的类名列表,并提供以下颜色作为示例:
cast => '#339999',
comment => '#008080',
core => '#FF0000',
double => '#999999',
heredoc_content => '#FF0000',
interpolate => '#999999',
keyword => '#0000FF',
line_number => '#666666',
literal => '#999999',
magic => '#0099FF',
match => '#9900FF',
number => '#990000',
operator => '#DD7700',
pod => '#008080',
pragma => '#990000',
regex => '#9900FF',
single => '#999999',
substitute => '#9900FF',
transliterate => '#9900FF',
word => '#999999',
以下代码生成一个自包含的 HTML 页面,其源代码使用给定的样式设置样式:
#!/usr/bin/env perl
use strict;
use warnings;
use PPI;
use PPI::HTML;
my %colors = (
cast => '#339999',
comment => '#008080',
core => '#FF0000',
double => '#999999',
heredoc_content => '#FF0000',
interpolate => '#999999',
keyword => '#0000FF',
line_number => '#666666',
literal => '#999999',
magic => '#0099FF',
match => '#9900FF',
number => '#990000',
operator => '#DD7700',
pod => '#008080',
pragma => '#990000',
regex => '#9900FF',
single => '#999999',
substitute => '#9900FF',
transliterate => '#9900FF',
word => '#999999'
);
my $highlighter = PPI::HTML->new(page => 1, line_numbers => 1, colors => \%colors);
my $perl_doc = PPI::Document->new(
do {
local $/;
open 0;
\ <0>;
}
);
print $highlighter->html($perl_doc);
如果你不使用page => 1
构造函数中的选项,你只会得到一个没有 CSS 的 HTML 片段。在这种情况下,您需要您的站点样式表来包含必要的样式。
另一方面,您可以使用HTML::TokeParser::Simple 简单地对 HTML 片段进行后处理:
#!/usr/bin/env perl
use strict;
use warnings;
use PPI;
use PPI::HTML;
use HTML::TokeParser::Simple;
my %colors = (
# as above
);
my $highlighter = PPI::HTML->new(line_numbers => 0);
my $html = $highlighter->html(\ do { local $/; open 0; <0> });
print qq{<pre style="background-color:#fff;color:#000">},
map_class_to_style($html, \%colors),
qq{</pre>\n}
;
sub map_class_to_style {
my $html = shift;
my $colors = shift;
my $parser = HTML::TokeParser::Simple->new(string => $html);
my $out;
while (my $token = $parser->get_token) {
next if $token->is_tag('br');
my $class = $token->get_attr('class');
if ($class) {
$token->delete_attr('class');
if (defined(my $color = $colors->{$class})) {
# shave off some characters if possible
$color =~ s{
\A \#
([[:xdigit:]])\1
([[:xdigit:]])\2
([[:xdigit:]])\3
\z
}{#$1$2$3}x;
$token->set_attr(style => "color:$color");
}
}
$out .= $token->as_is;
}
$out;
}
顺便说一句,这是一个“独立的例子”:一个无需我跳过任何箍即可运行的例子。您的程序无法运行,因为您将其留给了试图帮助您生成$perl_block
.