How do I call a function name that is stored in a hash in Perl?

后端 未结 3 1852
情深已故
情深已故 2020-12-10 16:00

I\'m sure this is covered in the documentation somewhere but I have been unable to find it... I\'m looking for the syntactic sugar that will make it possible to call a metho

相关标签:
3条回答
  • 2020-12-10 16:26

    Is there a reason you are storing subroutine names instead of the references to code?

    e.g.

    use strict; use warnings;
    
    package Foo;
    sub foo { print "in foo()\n" }
    
    package main;
    my %hash = (func => \&Foo::foo);
    
    $hash{func}->();
    

    You won't be passing the class name, but if that's important to you, you can use something like

    my %hash = ( func => sub { return Foo->foo(@_) } );
    
    0 讨论(0)
  • 2020-12-10 16:33
    Foo->${\$hash{func}};
    

    But for clarity, I'd probably still write it as:

    my $method = $hash{func};
    Foo->$method;
    
    0 讨论(0)
  • 2020-12-10 16:44

    Have you tried UNIVERSAL's can method? You should be able to implement something like this:

    ## untested
    if ( my $code = $object->can( $hash{func} ) ) {
        $object->$code();
    }
    

    I made a useless, one-line example to demonstrate:

    perl -MData::Dumper -le 'my %h = ( f => "Dump" ); my $o = Data::Dumper->new( [qw/1 2 3/] ); my $ref = $o->can( $h{f} ); print $o->$ref()'
    
    0 讨论(0)
提交回复
热议问题