Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Code on web in color!

by mushu (Initiate)
on Nov 15, 2003 at 01:47 UTC ( #307281=snippet: print w/replies, xml ) Need Help??
Description: Your own Perl code displays itself with colored tags on a web page! Best if the entire web page is a CGI.
# display this Perl CGI code!
open (HIN,"code.pl") or die "Unable to read $0 file: $!\n";
  @code=<HIN>;
close (HIN);
foreach (@code) {
  # prevent html code from activating
  s/&/&amp;/g unless /\x26\x26/;
  s/</&lt;/g;
  # colorize comments in the code
  s@#(.*)$@<span style="color:green;">#$1</span>@g if /#\s/&&!/#\(/;
  # colorize certain Perl keywords
  s@^#!(.+)@#<span style="color:purple;">!$1</span>@;
s@(\s*print\s*|elsif|eq\s|ne\s|foreach|while|open\s|close\s|if\s|use\s
+|die\s|\sor\s)@<span style="color:red;">$1</span>@ig unless /\(print/
+;
  s@(\x26\x26\s|\x2d>|\x3d>|\x2e=|\x7c\x7c\s|\x3a\x3a|\x2d\x2d|\x2b\x2
+b)@<span style="color:#CC33FF;">$1</span>@g;# && -> => .= || :: -- ++
  # colorize variables
  s@([\$\@]\w+)@<span style="color:blue;">$1</span>@g; # vars
  s@([\$\@][!_|])@<span style="color:blue;">$1</span>@g; # $! $_ $| @!
+ @_ @|
  # add this changed code to the stream
  $purl.=$_;
}
print "<font size=-1><pre>$purl</pre></font>";
# end
Replies are listed 'Best First'.
Re: Code on web in color!
by jeffa (Bishop) on Nov 15, 2003 at 16:34 UTC
    Congradulations! You reinvented Perl::Tidy. :)
    use strict; use warnings; use Perl::Tidy; use CGI qw(:standard); open FH, '<', '/path/to/perlfile.pl' or die $!; my $content = do {local $/;<FH>}; my $html; perltidy( source => \$content, destination => \$html, argv => '-html -npod -css=/path/to/perltidy.css', errorfile => '/dev/null', ); print header, start_html( -title => 'Colorized Perl', -style => { src => '/URL/to/perltidy.css' }, ), $html, end_html, ;
    Here is my perltidy.css file should you want to use it.

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
      Oh well...I thought it was cool anyway...thanks for pointing that out. At least my code doesn't need the overhead of a library. :)
Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://307281]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (2)
As of 2020-06-02 06:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you really want to know if there is extraterrestrial life?



    Results (13 votes). Check out past polls.

    Notices?