![]() |
|
Perl-Sensitive Sunglasses | |
PerlMonks |
Re: use Mojo::IOLoop::Subprocess - cannot pass argument to the subprocessby haukex (Archbishop) |
on Mar 29, 2023 at 10:15 UTC ( #11151319=note: print w/replies, xml ) | Need Help?? |
I want to get an idea of what I do wrong The problem with your first piece of code boils down to sub {}->(). This creates an anonymous sub and then immediately calls it, and ->run_p() gets the return value of this sub as its argument instead of the sub itself, as it should. This shows how important SSCCE along with the Basic debugging checklist are, especially boiling down the code and adding more print statements. If you inspect the output of the following code, you'll see how the subs are being called immediately in the same process as the IO loop.
Output:
and how to make it work, please! Some frameworks allow passing arguments to functions like this, but I don't see anything in the Mojo::IOLoop::Subprocess documentation to indicate that Mojo does. So the answer is as you have already discovered: closures. If you have a complex function that you want to call with different arguments in the subprocess, then simply write it as a separate sub and call it from the closure (e.g. ->run_p(sub { my_complex_func($arg1, $arg2) })). I already laid out the above code as a closure, so all you need to do for it to work is simply remove the ->($i) in the above, and the output is what you probably expect:
In Section
Seekers of Perl Wisdom
|
|