I'm using Keyword::Simple to interface with the Perl keyword API to inject some custom code. Problem is, if my custom code has newlines in it, any errors in the code will be reported from the wrong line in the original file. For example:
# KWTest.pm
package KWTest;
use strict;
use warnings;
use Keyword::Simple;
sub import {
my $class = shift;
Keyword::Simple::define mydie => sub {
my $ref = shift;
substr $$ref, 0, 0, qq{\n\n\n\n\n die "oh noes!!!!"};
};
}
1;
Then
perl -MKWTest -E 'mydie'
oh noes!!!! at -e line 6.
I know that perl
will respect #line
directives to change the reported line number, but in order to inject these in generated code I would need to know the pre-munged line number first.
I suppose I could also do it by just making sure my generated code contains no newlines, but that seems less fun.
The trick is when you're parsing code, count how many line breaks you skip over, and then when you inject code, inject the same number of line breaks, and don't inject any unnecessary line breaks. It's a bit of work, but it can be done.