發新話題

如何將Perl代碼著色

如何將Perl代碼著色

先決條件
cpan Syntax::Highlight:erl
代碼解釋
perldoc Syntax::Highlight:erl
perldoc裡或許解釋清楚了,但是蠻長了,我沒耐心看。使用裡面的代碼一點反應都沒有。
use Syntax::Highlight:erl;

my $formatter = new Syntax::Highlight::Perl;
print $formatter->format_string($my_string);
不想仔細看完全文,最主要是我懶,看英文頭痛得很。
還好可以Search, 找到了Coloring perl code in HTML。
對著那代碼,改寫了些許顏色。將它span裡改寫成使用class而不是style.這樣比較容易知道哪些詞是屬於哪一部分。
完成後的代碼如下。現炒現賣,直接將它著色。
打算遲些時候將它做為Eplanet的新功能。
highlightperl.css - 此CSS文檔可隨意更改。

.vs { color:#080; }
.va { color:#f70; }
.vh { color:#80f; }
.vt { color:#f03; }
.sub { color:#980; }
.qr { color:#ff8000; }
.str { color:#000; }
.cm { color:#008080;font-style:italic; }
.cmp { color:#014;font-family: garamond,serif;font-size:11pt; }
.bw { color:#3A3; }
.pk { color:#900; }
.nb { color:#f0f; }
.op { color:#000; }
.sym { color:#000; }
.kw { color:#00f; }
.bo { color:#f00; }
.bf { color:#001; }
.char { color:#800; }
.dr { color:#399;font-style:italic; }
.lb { color:#939;font-style:italic; }
.ln { color:#000; }
highlight.pl
#!/usr/bin/perl -T
use strict;
use warnings;
use CGI::Carp qw(fatalsToBrowser);
use CGI qw/:standard/;

my $cgi = new CGI;
print $cgi->header;

use Syntax::Highlight::Perl;

my $color_table = {
    'Variable_Scalar'   => 'vs',
    'Variable_Array'    => 'va',
    'Variable_Hash'     => 'vh',
    'Variable_Typeglob' => 'vt',
    'Subroutine'        => 'sub',
    'Quote'             => 'qr',
    'String'            => 'str',
    'Comment_Normal'    => 'cm',
    'Comment_POD'       => 'cmp',
    'Bareword'          => 'bw',
    'Package'           => 'pk',
    'Number'            => 'nb',
    'Operator'          => 'op',
    'Symbol'            => 'sym',
    'Keyword'           => 'kw',
    'Builtin_Operator'  => 'bo',
    'Builtin_Function'  => 'bf',
    'Character'         => 'char',
    'Directive'         => 'dr',
    'Label'             => 'lb',
    'Line'              => 'ln',
};

my $formatter = Syntax::Highlight::Perl->new();

$formatter->define_substitution('<' => '<',
                                '>' => '>',
                                '&' => '&'); # HTML escapes.

# install the formats set up above
while ( my ( $type, $class ) = each %{$color_table} ) {
        $formatter->set_format($type, [ qq~<span class=\"$class\">~, '</span>' ] );
}

print qq~<link rel="stylesheet" href="highlightperl.css" type="text/css" />~;
print '<pre>';
while (<DATA>) {
    print $formatter->format_string;
}
print "</pre>";

TOP

發新話題

本站所有圖文均屬網友發表,僅代表作者的觀點與本站無關,如有侵權請通知版主會盡快刪除。