Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restoring correct line number with Keyword::Simple

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.

like image 512
friedo Avatar asked Dec 11 '25 10:12

friedo


1 Answers

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.

like image 124
tobyink Avatar answered Dec 14 '25 08:12

tobyink



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!