是否可以讓下面的示例作業,以便通過標量變數存盤和呼叫子例程的名稱?
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');
uj5u.com熱心網友回復:
你可以把它放在一個哈希中:
my %hash;
$hash{'doit'} = \&doit;
$hash{'doit'}->('Mike');
或者您可以立即將其設為匿名子
my %hash = ( doit => sub { ... },
sayit => sub { .... },
....);
正如達達所說,它是一個標量值,所以它也可以放在一個標量變數中:
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';
擺脫它。
uj5u.com熱心網友回復:
根據對這個問題的回答: 如何優雅地呼叫名稱保存在變數中的 Perl 子例程?
你可以試試這個:
__PACKAGE__->can($action)->('john');
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/435090.html
標籤:perl
