The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.


Devel::ChangePackage - Change the package code is currently being compiled in


    package Foo;

    use Devel::ChangePackage;

    BEGIN { change_package 'Bar' }

    warn __PACKAGE__; # Bar


This module allows you to tell perl what package code should be compiled into. It's very similar to the package statement, but allows you to use variables and therefore to generate the package name to be used in any way you want. Just like package, this module only has compile-time effects.

Note that the effect of change_package is NOT lexically scoped the way that package is. For example:

    package Foo;

    sub routine { } # this gets defined in package Foo

    { package Bar; }

    sub other { } # this gets defined in package Foo, also


    package Foo;

    sub routine { } # this gets defined in package Foo

        BEGIN { change_package('Bar') }

    sub other { } # this gets defined in package Bar!

One way to think about this is changing the "argument" provided for the last package statement, or, if there was none yet, changing the default namespace from main to something else. It's not possible to make changes to the current namespace outside of the currently compiling scope.



    my $previous_package = change_package $new_package;

Changes the package code is being compiled in to $new_package. The name of the package things were compiled in before is returned.


With this module, it's possible to write the following code:

    package namespace::anon;

    use Devel::ChangePackage;

    my $i = 0;
    sub import {
        change_package 'namespace::anon::' . $i++;

Which you could later use like:

    use namespace::anon; # "package namespace::anon::0;"
    sub foo { ... } # namespace::anon::0::foo

    use namespace::anon; # "package namespace::anon::1;"
    sub foo { ... } # namespace::anon::1::foo

That is, every use namespace::anon will create a new "anonymous" package under the namespace::anon:: namespace and make that the current package. All code that is compiled afterwards, until the next change of package (by either the package statement or change_package) will live in that anonymous namespace.


Florian Ragwitz <>


This software is copyright (c) 2013 by Florian Ragwitz.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.