In Variables§

See primary documentation in context for The our declarator.

our variables are created in the scope of the surrounding package. They also create an alias in the lexical scope, therefore they can be used like my variables as well.

module M {
    our $Var;
    # $Var available here
}

# Available as $M::Var here.

Although lexical scoping with my has many advantages, sometimes we need to share more widely than within a given lexical scope, and using the is export trait can lead to namespace conflicts. Package scoping with our assigns symbols to distinct namespaces, avoiding conflicts. For example, to use the Cro clients for both HTTP and WebSockets in the same code, just refer to them as Cro::HTTP::Client and Cro::WebSocket::Client respectively.

Packages are introduced by package declarators, such as class, module, grammar, and (with caveats) role. An our declaration will make an installation in the enclosing package construct. Then users of your code (literally, with use) can refer to our-scoped entities in your package by providing the full package-qualified name of the entity.

All packages exist within a top-level package named GLOBAL and thus are globally visible, so declaring an our-scoped variable is declaring a global variable, even with namespace control. Anything that ends up visible via GLOBAL is effectively part of your API, so consider accordingly.

The kind of elements that are most likely to be shared default to package (our) scope, namely:

  • type declarations, including class, role, grammar, and subset

  • constants

  • enumerations

  • module declarations

Items that do not default to package scope:

  • subroutines default to lexical (my) scope, as discussed above

  • methods are scoped with has (only visible through a method dispatch)

  • variables have no default scope (although the most common choice here, my, is also the shortest to type)

In order to create more than one variable with package scope, at the same time, surround the variables with parentheses:

our ( $foo, $bar );

see also the section on declaring a list of variables with lexical or package scope.