如何从Perl中的变量值中按名称调用方法?

我有一个方法名称,我必须从参数中调用(从另一个脚本开始)-作为变量。 大大简化:

$method1 = "hello()";

我必须写:

hello();

但我不知道#method1中的名字。

我怎样才能做到这一点?

抱歉,我是Perl的初学者:)

评论
  • yvero
    yvero 回复

    确实不建议这样做,因为存在安全问题,但是您可以使用子例程的名称来调用它:

    my $method = "hello";
    {
      no strict 'refs';
      &{$method}();  # same as hello()
    }
    

    This &{...}() syntax “dereferences” the subroutine name and calls it.

    If you're calling methods on an object, you can skip the no strict 'refs' part:

    my $method = 'name';
    $object->$method();  # same as $object->name
    

    如果只想允许几个子例程,最好将它们存储在哈希表中:

    my %known_functions = (
      hello => \&hello,  # \& stores a reference to a subroutine 
      bye => \&not_hello,  # added benefit: renaming them
    );
    
    # define the functions somewhere
    sub hello { ... }
    sub not_hello { ... }
    
    # can't access secret methods unless they are added to the hash table
    sub secret { ... }
    
    # use a hash lookup and call the method
    my $method = 'hello';
    $known_functions{$method}();