我想将带有参数的子例程推入堆栈,但是我无法弄清楚语法。考虑一个没有参数的工作示例:
#!/usr/bin/perl -w
use strict;
use warnings;
sub hi { print "hi\n"; }
sub hello { print "hello\n"; }
sub world { print "world\n"; }
my @stack;
push (@stack, \&hi );
push (@stack, \&hello);
push (@stack, \&world);
while (@stack) {
my $proc = pop @stack;
$proc->();
}
当我运行代码时:
% ./pop-proc.pl
world
hello
hi
现在我的问题是,如果子例程看起来像这样:
sub mysub
{
chomp( my( $arg ) = @_ );
print "$arg\n";
}
我想用参数推送子例程,例如:
mysub("hello");
mysub("world");
非常感谢您的投入。
使用匿名子(甚至可能是闭包)。
push @stack, sub { mysub("hello") };
push @stack, sub { mysub("world") };
例如,
sub hi { say "@_" }
my $arg = "Hello";
my $sub = sub { hi($arg, @_) };
$sub->("World"); # Hello World
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句