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

Hello,

I am using Parallel ForkManager and I would like to use a more complex callback to run on finish, so I would like to define it before hand to make my code more readable. When I do this however I get the following error:

Can't use string ("1") as a subroutine ref while "strict refs" in use +at $HOME/local/perl/lib/perl5/site_perl/5.12.3/Parallel/ForkManager.p +m line 561 (#1) (F) Only hard references are allowed by "strict refs". Symbolic refer +ences are disallowed. See perlref.
I don't understand what's going on. Can somebody explain? Below is a minimal example to reproduce the error:
use strict; use warnings; use diagnostics; use Parallel::ForkManager; my $pm = new Parallel::ForkManager(2); # This works pm->run_on_finish( sub { print "Hello!\n"; } ); # This doesn't #sub hello { print "Hello!\n"; } #$pm->run_on_finish( &hello ); foreach my $child ( 0 .. 4 ) { my $pid = $pm->start and next; $pm->finish; } $pm->wait_all_children;

Replies are listed 'Best First'.
Re: Problem with ForkManager
by BrowserUk (Patriarch) on May 10, 2011 at 18:11 UTC

    This: &hello calls The subroutine named hello. You need \&hello to obtain the address.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Problem with ForkManager
by chrestomanci (Priest) on May 10, 2011 at 18:38 UTC

    You need to pass in a function reference to run_on_finish(). You could write:

    my $hello_ref = sub { print "Hello!\n"; }; $pm->run_on_finish($hello_ref);
    or:
    sub hello { print "Hello!\n"; } $pm->run_on_finish(\&hello);
      Wonderful, thanks. I would never have gotten it.
Re: Problem with ForkManager
by locked_user sundialsvc4 (Abbot) on May 11, 2011 at 01:55 UTC

    Just as an aside ... you will from time to time encounter some code (e.g. in CPAN...) which is designed to allow you to designate the subroutine to be called using either a string or a code-reference.   The code in question is designed so that, if given a string, it treats that string as a method name, and it tries to call that method against some object that has also been provided.   As usual, “TMTOWTDI.™”