| Perl Weekly Challenge #45 Task #2, Source Dumper |
The Source Dumper dumps the source code of itself. For my Blog of the PWC I use syntax highlighting. The perl program I use for the syntax highlighting I included in the Source Dumper of my Perl5 solution. This is a simple add-on with Text::VimColor.
Some highlights:
Perl5, Perl6 and Python solution.
Syntax Highlighting with Text::VimColor.
Program name with $0, $*PROGRAM and __file__
Simple line by line file reading.
# ./ch-2.pl - Execution of program
# ./ch-2.pl help - Help on parameters
# ./ch-2.p6 - Execution of program
# ./ch-2.py - Execution of program
# ./ch-2.pl | diff - ch-2.pl - Should result in no difference
# ./ch-2.p6 | diff - ch-2.p6
# ./ch-2.py | diff - ch-2.py
# perldoc ch-2.pod - POD
Write a script that dumps its own source code. For example, say, the script name is ch-2.pl then the following command should returns nothing.
$ perl ch-2.pl | diff - ch-2.pl
The printing of the Source Code is done with open(IN,$0) the file, a while loop while(IN) { print; } together with print and to close the file. Here the program name is in var $0.
The biggest part of the code is not needed for the PWC. It is a Source Dumper in HTML with Syntax Highlighting. This is done with the module Text::VimColor rather easy. You can print a full HTML page or only the source code part of the HTML. Some extra code is spent for the line numbers. Allthough Text::VimColor has an option for line numbers, it did not work. So I added the line numbers for myself.
This is the code part needed for PWC, like described above:
35 open(IN,$0) or die "Cant open $0\n";
36 while(<IN>) { print; }
37 close IN;
Some Highlights are:
Text::VimColor for Synthax Highlighting.
$0 for the program name,
while(IN) for the loop,
|
I translated the necessary part for PWC to Perl6. And let me mention some parts different to Perl5 here. May-be things could be solved easier? But for me as a beginner in Perl6, this is what I found first.
$*PROGRAM for the program name.
my $fh = open :r, $*PROGRAM; In Perl6 are used attributes with double-colons everywhere, here ":r". This can become difficult for me to swallow.
while ( ! $fh.eof; ) { While loop asks for not eof().
$str = $fh.get; And get reads without newline.
|
Because the code is not too complicated, let me mention some points. Put in mind that I am a beginner in Python, so any other Python programmer may wonder:
__file__ for the program name.
print(line), the comma at the end ommits newline. Otherwise newline is printed twice, first read from file and second an automatic newline from print.
for line in fh: I used a for loop, because this is what I found in the net.
|
Chuck
| Perl Weekly Challenge #45 Task #2, Source Dumper |