Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Import pragmas like strict and warnings into callers lexical scope

by youwin (Beadle)
on Feb 11, 2011 at 19:04 UTC ( [id://887663]=perlquestion: print w/replies, xml ) Need Help??

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

Oh wise and omniscient monks,

Im trying to understand why this works to import strict into the callers package:

# Foo.pm package Foo; sub import { strict->import; } # script use Foo; $yup = 5; # bang! (Global symbol "$yup" requires explicit...)

I know that normally to import package based modules, you can write something like this:

# Foo.pm package Foo; sub import { my $caller = caller; eval "package $caller; use Data::Dumper;"; } # script use Foo; print Dumper(\@ARGV); # $VAR1 = ...

Which makes sense because the use statement thinks it in the callers package. strict is strange because it imports into the lexical scope of the caller, and I thought that would be the block of the import routine in the first example above. So how does it know to enable strict for the callers lexical scope?

Replies are listed 'Best First'.
Re: Import pragmas like strict and warnings into callers lexical scope
by ikegami (Patriarch) on Feb 11, 2011 at 19:44 UTC

    All strict->import (normally called via use strict) does is modify global var $^H. The compiler uses $^H to determine if it should throw strict errors, among other things.

    The compiler localises $^H to the block being compiled. This is what produces the lexical scoping of the pragma.

    { # $^H is localised by the compiler # when it compiles this. use strict; # Changes $^H ... } # $^H is restored by the compiler # when it compiles this, # undoing changes in strictures.

    In your example, the block being compiled when strict->import is called is your script's file block, so the strictures stay in effect until the end of the file.

    Similarly scoped hash %^H is available to modules that want to be lexical pragmas without having to fight Perl for the limited bits in $^H.

    Update: Added code example. Added mention of %^H.

      Is it special that Perl restores $^H at the end of the enclosing block? Like could I write an import statement that does the same with a different global variable ($main::G for instance)?
        It's special to $^H and %^H, but %^H was created to give you access to that behaviour
        $^H{'mypragma'} = ...;
        $^H{'mypragma::G'} = ...;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://887663]
Approved by ww
Front-paged by moritz
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (2)
As of 2024-04-26 07:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found