How can I name a long package name without affecting the main package?

If I have a really long package name, I can hide this package by writing to the symbol table:

BEGIN {
    # Make "Alias" be an alias for "Some::Really::Long::Package";
    *Alias:: = \*Some::Really::Long::Package::;
    # Equivalent to:
    # *main::Alias:: = \*Some::Really::Long::Package::;
}

This is something that kind of Package::Aliasdoes for you internally. However, it stinks because it ticks the package main. How can I make an alias affect only the current package and be able to use only an alias in the package? I tried changing the alias definition to

*Short::Alias:: = \*Some::Really::Long::Package::;

But then I have to use Short::Alias->myMethod()instead Alias->myMethod().

use strict;
use warnings;

package Some::Really::Long::Package;

sub myMethod {
    print "myMethod\n";
}

package Short;

BEGIN {
    # Make "Alias" be an alias for "Some::Really::Long::Package";
    *Short::Alias:: = \*Some::Really::Long::Package::;
}

# I want this to work
Alias->myMethod();

package main;

# I want this to not work
Alias->myMethod();

Bonus points if both Alias->myMethod()and Alias::myMethod()are working in a package Short, rather than in main.

+4
source share
1

main, "package-local"

package Short;

use constant Alias => 'Some::Really::Long::Package'; # create alias
Alias->myMethod(); # correctly calls myMethod() of package Some::Really::Long::Package

, ,

package Short;

sub Alias { Some::Really::Long::Package:: } # create alias
Alias->myMethod(); # correctly calls myMethod() of package Some::Really::Long::Package

. , Alias->myMethod() main, ,

"myMethod" "Alias" (, "Alias"?)

%main:: %:: , Alias::.


, package, $alias Some::Really::Long::Package. $alias Short, :

package Short;
{
   my $alias = Some::Really::Long::Package::; # create alias
   $alias->myMethod(); # correctly calls myMethod() of package Some::Really::Long::Package
}

EDIT ( ):

:

Alias->myMethod() Alias::myMethod() Short, main?

.

->, ::. , perl, -, , , Alias, ::, Alias main:

package Short;

Alias::myMethod();           # if you call myMethod(), you actually call it ...

::Alias::myMethod();         # ... like this, which is equivalent ...

main::Alias::myMethod();     # ... to this

, . perl - Foo::, main, () . , , Alias::myMethod() Alias:: main.

, - Package::Alias . , , main.

, , , , Package::Alias, main, , , .

+5

Source: https://habr.com/ru/post/1657440/


All Articles