in reply to Re: Debugging preprocessor
in thread Debugging preprocessor

Indeed, Smart::Comments is similar. However, Debug::Filter::PrintExpr focuses on these points:

For my personal needs, these are not fully covered by Smart::Comments

So here it is:

package Debug::Filter::PrintExpr; use strict; use warnings; use Filter::Simple; our (@h, $p); sub gen_print { my ($self, $type, $label, $expr, $fh) = @_; # resulting code, with EXPR literally substituted by # the value of $expr and all in one single line: # # $: # { # local ($\, $,); # print 'line ', __LINE__, ':', ' EXPR = ', "'", # scalar(EXPR), "'", "\n"; # } # # @: # { # local ($\, $,); # print 'line ', __LINE__, ':', ' EXPR = ', "('", # join("', '", (EXPR)), "')", "\n"; # } # # %: # { # local ($\, $,); # print 'line ', __LINE__, ':', ' EXPR = '; # local (@Debug::Filter::PrintExpr::h, $Debug::Filter::PrintExp +r::p); # push @Debug::Filter::PrintExpr::h, $Debug::Filter::PrintExpr: +:p # while $Debug::Filter::PrintExpr::p = [each (EXPR)], # defined $Debug::Filter::PrintExpr::p->[0]; # print '(', (join ', ', # map {"'$_->[0]' => '$_->[1]'"} @Debug::Filter::PrintExpr: +:h), # ')', "\n"; # } # # quotes q and qq are for code generation # quotes " and ' are for generated code my $stmt = q[{local ($\, $,); print ]; $stmt .= qq{$fh } if $fh; $stmt .= $label ? qq{'$label'} : q{'line ', __LINE__, ':'}; if ($expr) { $stmt .= qq{, ' $expr = '}; if ($type eq '$') { $stmt .= qq{, "'", scalar($expr), "'"}; } elsif ($type eq '@') { $stmt .= qq{, "('", join("', '", ($expr)), "')"}; } elsif ($type eq '%') { my $h = q{@} . $self . q{::h}; my $p = q{$} . $self . q{::p}; $stmt .= qq{; local ($h, $p); }; $stmt .= qq{push $h, $p }; $stmt .= qq{while $p = [each ($expr)], }; $stmt .= qq{defined $p} . q{->[0]; }; $stmt .= q{print '(', (join ', ', }; $stmt .= q{map {"'$_->[0]' => '$_->[1]'"} }; $stmt .= qq{$h), ')'}; } } $stmt .= q[, "\n";}]; return $stmt; } FILTER { my ($self, %opt) = @_; s/ ^\h*\# (?<type>[%@\$]) \{\h* (?<label>\w+:)? \h* (?<expr>[^'\v]+)? \}\h*$ / gen_print($self, $+{type}, $+{label}, $+{expr}, $opt{-out}) /gme +x; print if $opt{-debug}; }; 1; __END__ =head1 NAME Debug::Filter::PrintExpr - Convert comment lines to debug print statem +ents =head1 SYNOPSIS use Debug::Filter::PrintExpr; my $s = 'a scalar'; my @a = qw(this is an array); my %h = (key1 => 'value1', key2 => 'value2'); #${$s} #@{@a} #%{%h} #${ calc: @a * 2 } When the program is run, the comment lines will produce an output like + this: line 12: $s = 'a scalar' line 13: @a = ('this', 'is', 'an', 'array') line 14: %h = ('key1' => 'value1', 'key2' => 'value2') calc: @a * 2 = '8' =head1 DESCRIPTION =head2 The Problem Providing debug output often results in a couple of print statements t +hat output the value of some expression and some kind of description. When the program is finished, these statements must be made conditiona +l on some variable or turned into comments. Often the contents of arrays or hashes need to be presented in a readable way, leading to repeated lines of similar code. C programmers use the preprocessor to solve this problem. As Perl has it's own filter mechanism for preprocessing, this leads to a similar solution in Perl. =head2 A Solution The Filter::Simple module by Damian Conway provides a convenient way of implementing Perl filters. Debug::Filter::PrintExpr makes use of this module to transform special +ly formed comment lines into print statements for various debugging purposes. Just by removing the "use" of Debug::Filter::PrintExpr completely or disabling it partially by no Debug::Filter::PrintExpr; all these lines (or a part of them) lose their magic and remain simple comments. The comment lines to be transformed must follow this format: # I<sigil> { [I<label>:] [I<expression>] } or more formally must be matched by the following regexp: ^\s*#([$@%]){\s*(\w+:)?\s*([^']+)?}\s*$ where $0 represents the sigil, $1 an optional label and $2 an optional expression. If the label is omitted, it defaults to C<line nnn:>, where nnn is the line number in the program. The sigil determines the output format of the given expression: =over 4 =item $ The expression is evaluated in scalar context and printed inside single quotes; =item @ The expression is evaluated in list context and the elements of the list are printed inside single quoted, separated by commas and gathere +d in parentheses. =item % The expression is used as argument in a while-each loop and the output consists of pairs of the form 'key' => 'value' inside parentheses. =back The forms #${} and #@{} may be used for any type of expression and inside the #%{} form, arrays are permitted too. With the varibles $s, @a and %h defined as listed above, it is possibl +e to use: #@{scalar_as_array: $s} #${array_as_scalar :@a} #@{hash_as_array: %h} #%{array_as_hash: @a} and receive these results: scalar_as_array: $s = ('this is a scalar') array_as_scalar: @a = '4' hash_as_array: %h = ('k1', 'v1', 'k2', 'v2') array_as_hash: @a = ('0' => 'this', '1' => 'is', '2' => 'an', '3' +=> 'array') If the expression is omitted, only the label will be printed. Any valid sigil may be used in this case. Requirements for the expression are: =over 4 =item 1. It must be a valid Perl expression. =item 2. It must not contain single quotes. (You may use q{} instead.) =item 3. In case of the #%{}-form, it must be a valid argument to the each() builtin function, i.e. it should resolve to an array or hash. =back A PrintExpr will be resolved to a block and therefore may be located anywhere in the program where a block is valid. Do not put it in a place, where a block is required (e.g. after a conditional) as this would break the code when running without the filter. =head2 Arguments to Debug::Filter::PrintExpr The use-statement for C<Debug::Filter::PrintExpr> may contain a hash of options: use Debug::Filter::PrintExpr (-out => 'STDERR', -debug => 1); =over 4 =item -out This option is used as the name of the file handle in the generated print statements. Note that the argument to C<-out> is not a file handle, but a string containing the name of the file handle. =item -debug When this option is set to true, the resulting source code after comment transformation is written to the default output file handle. Only the parts of source where Debug::Filter::PrintExpr is in effect are printed out. =back =head1 AUTHOR Joerg Sommrey =head1 LICENCE AND COPYRIGHT Copyright (c) 2018, Joerg Sommrey. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 DISCLAIMER OF WARRANTY BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WH +EN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. TH +E ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. =cut