Tricky localization/scope question

Andy Wardley abw at wardley.org
Tue Jul 28 06:24:44 BST 2009


On 28 Jul 2009, at 01:01, Randy J. Ray wrote:
> The tricky part that I can't seem to quite get right, is how to  
> properly
> localize the changes made to @INC so that it gets properly restored  
> when the
> scope exits. That is, I don't want the user to have to explicitly  
> "undo" their
> previous calls.

Let me see if I understand... you want code that does the equivalent  
of this:

     {
         local @INC = @INC;
         local %INC = %INC;
         ...your code...
     }

But you want that C<local %INC = %INC> to be hidden away and performed  
as part of
the call to C<test_without 'Compress::Zlib'>.

As far as I know, there's no way to "inject" a local variable into  
another scope
(i.e. from test_without() into the caller) from Perl.  Maybe it's  
possible from XS,
but probably not without deep monkeying around (although I would love  
to be proved
wrong on this).

However you could invert the problem with a function that takes a  
block and adds
the C<local> lines before calling it;

     sub local_inc(&) {
         local @INC = @INC;
         local %INC = %INC;
         $_[0]->();
     }

Then:

     local_inc {
         test_without 'Compress::Zlib';
         # ...etc...
     };

This will localise any changes to @INC/%INC on the way into the block  
and restore
them on the way out.

A



More information about the london.pm mailing list