in reply to subroutines and namespace

I suspect I have overlooked something major in the discussion here because when I was faced with (almost) the identical situation I just did:

package whatever; ... @EXPORT = qw( $routine ); $routine = q^ $thing = something+something_else; lots and lots of code; ^; sub routine [ my ($thing, $other_thing) = @_; eval $routine; } package main; my $thing; my $other_thing; eval $routine;

If you want to run routine in local scope, eval $routine it. If you don't want it messing with your variables, call it with routine()

____________________
Jeremy
I didn't believe in evil until I dated it.

Replies are listed 'Best First'.
Re (tilly) 2: subroutines and namespace
by tilly (Archbishop) on Nov 03, 2001 at 11:37 UTC
    Warning. That eval solution needs error checks. Else you could get very confused working out why you are getting no result, when the problem is that $routine expects to be sharing some variables with its environment, the environment doesn't have them, and strict finds this to be a situation worth complaining about.

    (Just to list one non-obvious way that a non-trivial error in $routine may need to be handled.)

    UPDATE
    Re the reply, I understand fully. I just like pointing these things out because you have to expect people to just lift code from here directly without understanding the issues. So if you are posting it as a suggestion, it should look like production code.

    That said, I find the eval solution painful on the face of it. I would prefer to solve that with just using Filter::Simple and a few well-chosen macros. If I was going to solve things that way. Which I would probably avoid for reasons listed above...

      The perils of doing an off-the-cuff answer to a post. When I implemented it I eventually had buckets of error checks in the routine itself (e.g.  if defined) and checked the results with an or die "\$routine failed with error $@". I also had almost every second line printing into a log file (my personal favourite way of documenting code).

      But after that there's not much difference between the evals and real subs except some faulty code can stomp all over variables in your current namespace.

      ____________________
      Jeremy
      I didn't believe in evil until I dated it.