将带有参数的子例程推入Perl中的堆栈

时间:2017-07-04 19:18:53

标签: perl subroutine perl-data-structures

我想将带有参数的子程序推入堆栈,但我无法弄清楚语法。考虑一个没有参数的工作示例:

#!/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");

非常感谢您的意见。

2 个答案:

答案 0 :(得分:8)

使用匿名子(甚至可能是一个闭包)。

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

答案 1 :(得分:7)

我可能会做这样的事情,我创建一个元组来保存代码引用及其参数:

application(:didReceiveRemoteNotification)

我在那里使用v5.24 postfix dereference,但那是因为我无法自拔。这也有效,但现在我觉得它非常难看:

<ion-content style="top:0px">