Push subroutine with argument onto stack in Perl

I would like to push a subroutine with arguments onto the stack, but I cannot figure out the syntax. Let's see a working example with no arguments:

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

      

when i run the code:

% ./pop-proc.pl
world
hello
hi

      

Now my question is, what if the subroutine looked like this:

sub mysub 
{
    chomp( my( $arg ) = @_ );
    print "$arg\n"; 
}

      

and I would like to push subroutines with arguments like:

mysub("hello");
mysub("world");

      

Your input is highly appreciated.

+3


source to share


2 answers


Use an anonymous sub (which might even be a closure).

push @stack, sub { mysub("hello") };
push @stack, sub { mysub("world") };

      



For example,

sub hi { say "@_" }
my $arg = "Hello";
my $sub = sub { hi($arg, @_) };
$sub->("World");   # Hello World

      

+8


source


I could do something like this when I create a tuple to hold the code reference and its arguments:

use v5.24;

sub hi    { print "Hi @_\n";    }
sub hello { print "Hello @_\n"; }

my @stack;
push @stack, [ \&hi,    'Perl'     ];
push @stack, [ \&hello, 'Amelia'   ];
push @stack, [ \&hello, $ENV{USER} ];

while (@stack) {
    my( $proc, @args ) = pop( @stack )->@*;
    $proc->( @args );
}

      



I am using v5.24 postfix dereference but that is because I cannot help myself. This works too, but now I find it very ugly:

    my( $proc, @args ) = @{ pop( @stack ) };

      

+7


source







All Articles