You almost certainly want to add use Smart::Comments to modules containing such ones, and then flip the switch in your environment by setting $Smart_Comments accordingly.
Stamping, import hijacking monkey-patching is crazy.
But maybe you believe that. Let's say you have Foo.pm :
package Foo; use Exporter 'import'; our @EXPORT = qw/ foo /;
Common use:
$ perl -MFoo -e 'print foo, "\ n"'
024
Normal is boring and boring, of course. With run-foo we take bold, dashing steps!
#! /usr/bin/perl use warnings; use strict; BEGIN { unshift @INC => \&inject_smart_comments; my %direct; open my $fh, "<", $0 or die "$0: open: $!"; while (<$fh>) { ++$direct{$1} if /^\s*use\s+([AZ][:\w]*)/; } close $fh; sub inject_smart_comments { my(undef,$path) = @_; s/[\/\\]/::/g, s/\.pm$// for my $mod = $path; if ($direct{$mod}) { open my $fh, "<", $path or die "$0: open $path: $!"; return sub { return 0 unless defined($_ = <$fh>); s{^(\s*package\s+[AZ][:\w]*\s*;\s*)$} {$1 use Smart::Comments;\n}; return 1; }; } } } use Foo; print foo, "\n";
(Please excuse the compactness: I squeezed it so that everything was in an unprotected block.)
Output:
$ ./run-foo
### $ i: 0
### $ i: 1
### $ i: 2
### $ i: 3
### $ i: 4
024
& iexcl ;! Viva
With @INC hooks, we can replace our own or modified sources. The code monitors attempts to require modules directly used by the program. When hit, inject_smart_comments returns an iterator that yields one row at a time. When this tricky, sophisticated iterator sees the package declaration, it adds the invisible use Smart::Comments view to the piece, making it look as if it were in the module source.
When trying to parse Perl code with regular expressions, the code will break if the package declaration is not, for example, a separate line. Season to taste.