Perl5 リファレンス



       our EXPR
               An `our' declares the listed variables to be valid
               globals within the enclosing block, file, or
               `eval'.  That is, it has the same scoping rules as
               a "my" declaration, but does not create a local
               variable.  If more than one value is listed, the
               list must be placed in parentheses.  The `our'
               declaration has no semantic effect unless "use
               strict vars" is in effect, in which case it lets
               you use the declared global variable without
               qualifying it with a package name.  (But only
               within the lexical scope of the `our' declaration.
               In this it differs from "use vars", which is
               package scoped.)

               An `our' declaration declares a global variable
               that will be visible across its entire lexical
               scope, even across package boundaries.  The
               package in which the variable is entered is
               determined at the point of the declaration, not at
               the point of use.  This means the following
               behavior holds:

                   package Foo;
                   our $bar;           # declares $Foo::bar for rest of lexical scope
                   $bar = 20;

                   package Bar;
                   print $bar;         # prints 20

               Multiple `our' declarations in the same lexical
               scope are allowed if they are in different
               packages.  If they happened to be in the same
               package, Perl will emit warnings if you have asked
               for them.

                   use warnings;
                   package Foo;
                   our $bar;           # declares $Foo::bar for rest of lexical scope
                   $bar = 20;

                   package Bar;
                   our $bar = 30;      # declares $Bar::bar for rest of lexical scope
                   print $bar;         # prints 30

                   our $bar;           # emits warning


Perl5リファレンスに戻る