使用标量引用子程序
是否可以使下面的示例正常工作,以便通过标量变量存储和调用子例程的名称?
use strict;
use warnings;
sub doit {
my ($who) = @_;
print "Make us some coffee $who!\n";
}
sub sayit {
my ($what) = @_;
print "$what\n";
}
my $action = 'doit';
$action('john');
Is it possible to get the example below to work so that the name of the subroutine is stored and called via a scalar variable?
use strict;
use warnings;
sub doit {
my ($who) = @_;
print "Make us some coffee $who!\n";
}
sub sayit {
my ($what) = @_;
print "$what\n";
}
my $action = 'doit';
$action('john');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将其放入散列中:
或者您可以立即将其设为匿名子
正如 Dada 提到的,它是一个标量值,因此也可以将其放入标量变量中:
从技术上讲,您还可以将字符串放入标量中,并将其用作子例程:
但是,如果您使用
use strict
,就像您应该的那样,它不会允许您,并且会因错误而死亡:所以不要这样做。如果你想使用字符串来引用 subs,使用哈希是正确的方法。但如果你仍然想,你可以
逃脱它。
You could put it in a hash:
Or you could make it an anonymous sub right away
As Dada mentions, it is a scalar value, so it can also be put in a scalar variable:
Technically you can also put a string into a scalar, and use that as a subroutine:
But if you are using
use strict
, like you should, it will not allow you, and will die with the error:So don't do that. If you want to use strings to refer to subs, using a hash is the proper way. But if you still want to, you can
To get away with it.
根据这个问题的回答:
如何我优雅地调用一个名称保存在变量中的 Perl 子例程?
你可以尝试这个:
According to an answer to this question:
How can I elegantly call a Perl subroutine whose name is held in a variable?
You could try this: