Perl is a very flexible scripting language. There is also a demand scenario for reflection. Reflection is the conversion of a string to the corresponding language object.
(Do not consider the ultimate kill technique such as eval) 1. Reflection as a normal variable this is not supported, that is, you can not achieve
My $a = "B";
My $b = "123";
Print \ $a; # trying to get "123" is impossible.
The alternative is to use hash
My $b = ' 123 ';
My $c {' B '}= $b;
My $a = ' B ';
Print $c {$a}; #可以从 $a get ' 123 '
2. Functions that reflect functions Perl have some black magic. However, it is recommended that you try to access it by hash.
#反射函数
#根据字符串变量, the dynamic execution function (according to $fname call to Hello) use
strict;
My $fname = ' hello ';
Sub Hello ($) {
my ($n) =@_;
print "Hello $n \ n";
}
#hello (); #strict不允许. Reference
&hello (1) in situ, #正式的函数调用
Hello (2), #这么写也允许
#正规的函数引用
my $fname 3=\&hello; #\& delegate fetch function reference
& $fname 3 (3); #& execution
$fname 3-> (4);
#正规的做法. Register the function to hash first.
my%fh;
$fh {"Hello"}=\&hello;
$fh {"$fname"} (9); #再通过名字变量调用
#&{$fh {"$fname"}} (9), #也可以
#反射的黑魔法
"Hello" (5); #允许. But no use
# $fname (); #strict不允许
#&{$fname} (); #strict不允许
#\&{$fname}-> (); #strict不允许
&{\&{$fname}} (6); #这么写可以, but a little hard to understand
my $fname 2 = \ &{"Hello"}; #magictrick
& $fname 2 (7);
My $fname 1 = \&{$fname};
& $fname 1 (8); #前面的 & is required
3. The reflective module can be $mname by require; It's OK, but use not. Perl has no getattr function like Python, but it can be treated like a function reflection.
#!/usr/bin/perl use
findbin qw ($Bin);
Use Lib "$Bin";
My $mname = "foo1.pm"; #通过变量加载模块
#require Foo1;
Require $mname;
Foo1::bar ("a");
Foo1::blat ("B");
My $fname = "Foo1::blat";
My $fname 1 = \&{$fname}; #通过变量执行函数
& $fname 1 ("B");