稀疏文檔狀態:
對於您不想使用外部的樣式表,你可以提供的顏色作爲哈希參考案例,其中鍵是CSS類(一般匹配標記名稱)和值是顏色。
的POD爲PPI::HTML::CodeFolder有可以使用的類名的列表,並給出了作爲一個例子以下顏色:
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',
下面的代碼生成使用與its own source code一個自包含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
選項,你只會得到一個HTML片段沒有CSS。在這種情況下,你需要你的網站樣式表包含必要的樣式。
在另一方面,你可以使用HTML::TokeParser::Simple簡單post-process the HTML fragment:
#!/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
的內容的人員。
我投票根據OP的更新重新打開這個問題。請考慮投票重新開放。 – 2015-03-27 15:10:45