使用标量引用子程序

发布于 2025-01-10 09:53:17 字数 264 浏览 0 评论 0原文

是否可以使下面的示例正常工作,以便通过标量变量存储和调用子例程的名称?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ι不睡觉的鱼゛ 2025-01-17 09:53:17

您可以将其放入散列中:

my %hash;
$hash{'doit'} = \&doit;
$hash{'doit'}->('Mike');

或者您可以立即将其设为匿名子

my %hash = ( doit  => sub {  ... },
             sayit => sub { .... },
            ....);

正如 Dada 提到的,它是一个标量值,因此也可以将其放入标量变量中:

my $command = \&doit;
$command->('Mike');

从技术上讲,您还可以将字符串放入标量中,并将其用作子例程:

my $action = 'doit';
$action->('Mike');      # breaks strict 'refs'

但是,如果您使用use strict,就像您应该的那样,它不会允许您,并且会因错误而死亡:

Can't use string ("doit") as a subroutine ref while "strict refs" in use...

所以不要这样做。如果你想使用字符串来引用 subs,使用哈希是正确的方法。但如果你仍然想,你可以

no strict 'refs';

逃脱它。

You could put it in a hash:

my %hash;
$hash{'doit'} = \&doit;
$hash{'doit'}->('Mike');

Or you could make it an anonymous sub right away

my %hash = ( doit  => sub {  ... },
             sayit => sub { .... },
            ....);

As Dada mentions, it is a scalar value, so it can also be put in a scalar variable:

my $command = \&doit;
$command->('Mike');

Technically you can also put a string into a scalar, and use that as a subroutine:

my $action = 'doit';
$action->('Mike');      # breaks strict 'refs'

But if you are using use strict, like you should, it will not allow you, and will die with the error:

Can't use string ("doit") as a subroutine ref while "strict refs" in use...

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

no strict 'refs';

To get away with it.

2025-01-17 09:53:17

根据这个问题的回答:
如何我优雅地调用一个名称保存在变量中的 Perl 子例程?

你可以尝试这个:

__PACKAGE__->can($action)->('john');

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:

__PACKAGE__->can($action)->('john');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文