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

Is there any way of wrapping pragmas like 'use' the way you can wrap a subroutine. ie.
no strict refs; my $sub = *{Some::Package::function}{CODE}; *Some::Package::function = sub { my $retval = [ $sub->(@_) ]; print "wrappers don't kill, I do"; return $retval; }; use strict refs;

Replies are listed 'Best First'.
Re: wrapping 'use'?
by chromatic (Archbishop) on Oct 04, 2006 at 01:00 UTC

    Stick a coderef at the start of @INC, as documented in require.

Re: wrapping 'use'?
by ikegami (Patriarch) on Oct 04, 2006 at 04:59 UTC

    Yes, use curlies. Pragams (such as use strict and use warnings) are lexically scoped, so they only affect the block in which they are located and child blocks (the blocks which are enclosed by the block in which they are located).

    { no strict 'refs'; ... } # Previous setting resumes after curlies.

    The following is a version of your code that disabiles strict refs and warnings for the smallest scope possible:

    # Name of the function to wrap. my $sub_name = '...'; # Symbol table entry of the function we want to wrap. my $sub_glob = do { no strict 'refs'; \*$sub_name }; # Reference to the function we want to wrap. my $sub = \&$sub_glob; # The wrapper. my $wrapper = sub { ... $sub->(@_) ... }; # Replace function with its wrapper. { no warnings 'redefine'; *$sub_glob = $wrapper; }

    U: Added comments.