Perl: debugging subroutines stored in strings and called by eval

ⅰ亾dé卋堺 提交于 2019-12-11 06:29:11

问题


I do a lot of regex on file A. Based on my parsing, I create many subroutines and store them in a hash , $code --in subroutine f.

sub f
{
    #REGEX on file A
    $code = { "a0" => "sub { my $x = shift; .... return 0*x;}",
              "a1" => "sub { my $x = shift; .... return 1*x;}",
              ....
              "a9" => "sub { my $x = shift; .... return 9*x;}",
            }
}

The hash values of code are the generated subroutines and the keys are some other strings.

Then, using subroutine g, I do lots of regex on file B and get some keys and then call the corresponding subroutine from code by evaling $code{$key}($x).

sub g
{
    #REGEX on file B to get the keys and x`s
    foreach $keys{
        print $code{keys}($x) 
   }
}

I do this ugly job (instead of calling f) to avoid multiple regexing over A. However, this makes debugging sub f a tedious job --since I don't have the actual keys coming from B in A. Unless, I put some, printing statement in $code itself. I avoid doing this, since I'd rather to keep the functionality of $code as it is (with no LOG statement).

Any remedy for my problem?


回答1:


You can assign the name to local *__ANON__ (see Named anonymous subs at PerlMonks), or you can use Sub::Name (BTW, one of the suggestions in the linked thread).



来源:https://stackoverflow.com/questions/25319236/perl-debugging-subroutines-stored-in-strings-and-called-by-eval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!