Perl, dynamically include package

后端 未结 3 782
离开以前
离开以前 2020-12-18 05:22

Let\'s say I have a perl module file and I want to include and use it dynamically at runtime. Said module includes a class that I need to instantiate without knowing its nam

3条回答
  •  既然无缘
    2020-12-18 05:48

    my $module_var = 'module';
    eval "use $module_var; 1" or die $@;
    my $module_instance = $module_var->new();
    

    Note that the eval is a possible security hole. If $module_var contains code, it will get executed. One way around this is to use Class::MOP. Replace the eval line with:

    use Class::MOP;
    Class::MOP::load_class($module_var);
    

    If you don't want to require Class::MOP, you could copy the _is_valid_class_name function from it into your code, and just make sure that $module_var contains a valid class before you eval it. (Note that if you're using Moose, you're already using Class::MOP behind-the-scenes.)

提交回复
热议问题