简体   繁体   中英

How to interpret a string as Perl code and execute it without eval

I understand that "string-eval" can be used for it. But I am looking for some alternative to achieve it without eval . Reason being "string-eval" fail the Perl critic and as per client policy I can not use it.

What are some alternative to do that without eval ?

Here is what I am trying to do:

I am passing a dynamic generated code reference to a function. This function evaluates this code reference and assign the result to a variable.

Perl critic objects to string-eval because "interpreting a string as perl code and executing it" is generally a poor solution to any problem.

You can't work around it by just finding another function to do the same thing (well, you could, but that would be entirely missing the point).

Coderefs do not need eval to run. Simply dereference a coderef to invoke it. This is explained in perldoc perlref .

my $code = sub {
    my ($name) = @_;
    say "Hi, $name!";
};
$code->('rpg');

This works for me.

#!/usr/bin/perl
use strict;
use warnings;

sub exec_code {
    my ($c) = @_;
    return &{$c};
}

my $coderef = sub {
    print "Hello, from sub";
};

exec_code($coderef);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM