zhuce 发表于 2017-5-17 10:29:48

如何将Perl代码着色

http://www.fayland.org/journal/Highlight.html
 
先决条件
CPAN Syntax::Highlight::Perl
代码解释
perldoc Syntax::Highlight::Perl
perldoc里或许解释清楚了,但是蛮长了,我没耐心看。使用里面的代码一点反应都没有。
use Syntax::Highlight::Perl;
  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>";
页: [1]
查看完整版本: 如何将Perl代码着色