Control flow

PACKAGE#

Return the name of the package currently in effect at the point where the token appears.

__PACKAGE__ is a compile-time literal: the parser replaces it with a string constant naming whichever package the most recent package statement put into effect for this lexical scope. It does not look anything up at runtime, does not follow inheritance, and does not care what class the calling code is using — it is simply the name of the package that owns the source text it sits in.

Synopsis#

__PACKAGE__
__PACKAGE__->some_method(@args)
$__PACKAGE__::VERSION          # does NOT work — see Edge cases

What you get back#

A plain string containing the fully qualified package name (e.g. "My::Thing", "main"), interned at compile time. The value is a constant for the duration of the enclosing scope — it cannot change at runtime and does not depend on how the code is called.

Outside any explicit package declaration, the value is "main".

Global state it touches#

None. __PACKAGE__ is resolved at compile time from the lexical package in effect at its source location; it reads no interpreter state when executed and has no side effects.

Why use a token instead of writing the name#

Three reasons, in the order you hit them in practice:

  1. The file gets renamed or the package gets renamed and nothing else has to change. Every __PACKAGE__ updates automatically; every hand-typed "My::Thing" has to be found and edited.

  2. It is the only portable way to write “this class” inside a package block form, where the package ends at the closing brace and an inner helper cannot assume the file name matches.

  3. It composes with class methods cleanly: __PACKAGE__->new(...) in a constructor helper calls the right class whether the file is loaded directly or copied into a subclass that has not yet redefined the helper.

For the runtime equivalent — “what class is $self actually blessed into?” — use ref or, in use feature 'class' code, __CLASS__. They are not the same thing; see Edge cases.

Examples#

Read the current package inside a module:

package My::Thing;
say __PACKAGE__;                # My::Thing

Use __PACKAGE__ to reach a package variable without hard-coding the name — robust against renames:

package My::Thing;
our $VERSION = '1.23';

sub version_string {
    no strict 'refs';
    return ${ __PACKAGE__ . '::VERSION' };
}

Constructor helper that stays correct when copy-pasted into a subclass or when the package is switched with the block form:

package My::Widget {
    sub new {
        my ($class, %args) = @_;
        bless { %args, kind => __PACKAGE__ }, $class;
    }
}
# kind is always "My::Widget", even if someone calls
# My::Widget::SubClass->new and forgets to override `new`.

Debug trace that prints where a log line came from, without having to duplicate the package name in every message:

package My::Worker;
use v5.36;

sub log_debug {
    my ($msg) = @_;
    warn __PACKAGE__ . ": $msg\n";
}

Cross-package resolution with the block form — each __PACKAGE__ sees whichever package wraps it:

package Outer;
say __PACKAGE__;                # Outer

package Inner {
    say __PACKAGE__;            # Inner
}

say __PACKAGE__;                # Outer again

Edge cases#

  • Constant at compile time, not a variable. __PACKAGE__ is not a scalar; $__PACKAGE__ and ${__PACKAGE__} do not exist. It interpolates in double-quoted strings as the string it resolves to:

    package Foo;
    say "in @{[__PACKAGE__]}";     # in Foo
    say "in $__PACKAGE__";         # prints "in " — $__PACKAGE__ is undef
    

    The @{[ ... ]} idiom is the shortest way to interpolate it.

  • Symbolic reference to a package variable requires string concatenation, not interpolation of a sigil:

    no strict 'refs';
    my $v = ${ __PACKAGE__ . '::VERSION' };   # works
    my $v = ${"__PACKAGE__::VERSION"};        # WRONG — literal package
    
  • Not the same as ref $self. __PACKAGE__ is where the source was written; ref $self is what the object was actually blessed into. A method inherited from a base class returns the base class from __PACKAGE__ but the subclass from ref $self:

    package Base;
    sub who { (__PACKAGE__, ref $_[0]) }
    
    package Child;
    our @ISA = ('Base');
    
    say join " / ", Child->who;     # Base / Child
    

    When you want the class the method was invoked on, use ref on the invocant, __CLASS__ inside a class/method block, or take $_[0] / shift as the class name for a class method.

  • Block-form scoping. Inside package NAME { ... }, __PACKAGE__ is NAME; after the closing brace the previous value is restored. See the nested example above.

  • eval STRING captures its compile-time package. The string is compiled in the caller’s package, so __PACKAGE__ inside eval "..." is the package that called eval:

    package Foo;
    eval 'say __PACKAGE__';          # Foo
    
  • Before any package statement (top of a script, top of a one-liner), __PACKAGE__ is "main".

  • __PACKAGE__ does not mean “current class”. Under use feature 'class', the class name and the package name agree on the declaration line but can differ at a call site invoked on a subclass. Inside a method, prefer __CLASS__ when you want the class of the receiver.

Differences from upstream#

Fully compatible with upstream Perl 5.42.

See also#

  • package — the declaration that sets what __PACKAGE__ returns; every non-main value comes from one

  • __CLASS__ — the runtime counterpart for code inside a class block: returns the class of the invoking instance, which may be a subclass

  • ref — ask an object what class it was blessed into; the right tool when you have $self and want its actual class

  • caller — the calling package at runtime; use when you need the caller’s package, not your own

  • bless — the primitive that turns a reference into an object of a given package; typically paired with __PACKAGE__->new(...) style constructors

  • our — declares a lexical alias to a package variable in the current compile-time package (the same package __PACKAGE__ names)