in reply to Call subroutine of main namespace from package in Plack

Seems very odd but try

BEGIN { package main; sub test{ return scalar localtime; } } use Mypackage; sub { print "OK"; return [200, ["Content-Type"=>"text/html" ],[Mypackage::test2()]]; };
package Mypackage; sub test2 { ::test(); } 1;
poj

Replies are listed 'Best First'.
Re^2: Call subroutine of main namespace from package in Plack
by Thenothing (Sexton) on Apr 11, 2018 at 15:31 UTC
    Hi there, poj. Thanks for your code, that work, maybe this approach I tried to implement is bad design ? Thanks to everyone.

      Perl is an incredibly flexible language that gives the power to execute bad designs. Yours is quite bad, especially in a PSGI pipeline where responsibilities are well designed and compartmentalized; and I encourage you to abandon it immediately.

      You should not feel bad, though. It's one of the early "intuitive" things a lot of us, especially self-taught programmers, try to do. The other that is almost a rite of passage is using variables as variable names. Working with raw PSGI is quite ambitious. It's not designed to be for direct webwork but for package authors to use as a platform for their higher level kits which are then in turn used for webwork.

      If you break down your project into small bites and present them as questions here, you'll probably get terrific advice and code snippets directly on point. Right now you're mostly getting expert advice on how to do things no one but experts even knows how to do because, like wheelies in traffic, it RFC:SHOULDN'T be done. :P

      Update: fixed a grammar booger that was bothering me.

        This is kind of the response I wish I had time for today, but like all of us, sometimes firefighting in other areas in life take precedence.

        This answer, along with other answers, particularly AnomalousMonks post here spell it out for me.

        I'm still fire-fighting, so if nobody else gets a chance before I can, OP should be introduced into coderefs, and sending in subroutines as a parameter. Somehow I feel passing in function references to a call to a module's functions/methods fit in this case.

      Interestingly (for some definition of "interesting"), this also works and seems exactly equivalent (update: and reduces worries about phasing of BEGIN blocks, use statements and sub definitions, etc.):

      c:\@Work\Perl\monks\Thenothing>perl -le "use warnings; use strict; ;; use Mypackage; ;; print Mypackage::test2(); ;; print test(); " hiya @ Wed Apr 11 12:35:25 2018 hiya @ Wed Apr 11 12:35:25 2018
      File Mypackage.pm:
      package Mypackage; use warnings; use strict; sub main::test { return 'hiya @ ' . localtime; } sub test2 { ::test(); } 1;
      Oh, and by the way: Don't Do This! Others have suggested much better ways of organizing your code.


      Give a man a fish:  <%-{-{-{-<