Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

How can I call subroutines in an array

by ozgurp (Beadle)
on Jun 10, 2003 at 04:45 UTC ( #264536=perlquestion: print w/replies, xml ) Need Help??

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 (Bishop) 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"; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://264536]
Approved by Paladin
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2022-05-24 03:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (82 votes). Check out past polls.

    Notices?