ozgurp has asked for the wisdom of the Perl Monks concerning the following question:

use strict; use warnings; my @procs; sub a1 { print("a1\n"); } sub a2 { print("a2\n"); } @procs = (&a1, &a2); foreach (@procs) { $_; }
This code gives the following message

"Useless use of a variable in void context at C:\test.pl line 19."
what is the better way of doing this?

Replies are listed 'Best First'.
Re: How can I call subroutines in an array
by Chmrr (Vicar) on Jun 10, 2003 at 04:54 UTC

    It's hard to tell, but you're calling them when you think you're putting them into the array -- that is, at the @procs = (&a1, &a2) line. The solution to this problem is references, as discussed in perlref and perlreftut. As follows:

    use strict; use warnings; sub a1 { print("a1\n"); } sub a2 { print("a2\n"); } my @procs = (\&a1, \&a2); foreach (@procs) { $_->(); }

    perl -pe '"I lo*`+$^X$\"$]!$/"=~m%(.*)%s;$_=$1;y^`+*^e v^#$&V"+@( NO CARRIER'

Re: How can I call subroutines in an array
by dvergin (Monsignor) on Jun 10, 2003 at 04:55 UTC
    How's this:
    use strict; use warnings; sub a1 { print("a1\n"); } sub a2 { print("a2\n"); } my @procs = (\&a1, \&a2); foreach (@procs) { &$_; } # or for a more idiomatic approach # enter anonymous subs directly into the array: my @procs2 = (sub { print("this\n") }, sub { print("that\n") } ); foreach (@procs2) { $_->(); # alternate form to call subroutine ref }
    All of which prints:

        a1
        a2
        this
        that

    ------------------------------------------------------------
    "Perl is a mess and that's good because the
    problem space is also a mess.
    " - Larry Wall

Re: How can I call subroutines in an array
by eyepopslikeamosquito (Archbishop) on Jun 10, 2003 at 08:17 UTC

    Slightly different approach. Hey, variety is the spice of life!

    use strict; use warnings; sub Handler::a1 { print("a1\n"); } sub Handler::a2 { print("a2\n"); } for (1..3) { exists($Handler::{'a'.$_}) ? &{$Handler::{'a'.$_}} : print "no handler for $_\n"; }