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

守給你的承諾、 提交于 2019-11-28 11:17:21
Foo->${\$hash{func}};

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

my $method = $hash{func};
Foo->$method;

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(@_) } );

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