Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

What's the best way to use a module by an alias or short name?

In Python you can do "import foo.barista.bazoo.qux as fbbq". If I have a Perl module with a long name (ex. Foo::Barista::Bazoo::Qux), how can I refer to its contents using something like $fbbq::the_scalar instead of $Foo::Barista::Bazoo::Qux::the_scalar?

  • Comment on How can I use a module via a short name or alias?

Replies are listed 'Best First'.
Re: How can I use a module via a short name or alias?
by ikegami (Patriarch) on Feb 17, 2010 at 17:50 UTC
    use Package::Alias Fbbq => 'Foo::Barista::Bazoo::Qux';

    use aliased 'Foo::Barista::Bazoo::Qux' => 'Fbbq';

    use namespace::alias 'Foo::Barista::Bazoo::Qux' => 'Fbbq';

    sub Fbbq { Foo::Barista::Bazoo::Qux:: }

    I think only the first will actually meet your requirements. The second and third might be limited to class names (e.g. left of ->) like the fourth.

Re: How can I use a module via a short name or alias?
by ctilmes (Vicar) on Feb 17, 2010 at 17:44 UTC
Re: How can I use a module via a short name or alias?
by Fletch (Bishop) on Feb 17, 2010 at 17:51 UTC

    If they're your packages to begin with you can always tell Exporter that you want to (conditionally) export them into use'ers namespace. If they're not yours (but you're determined to go mucking about in someone else's namespace anyhoo) there's always local *fbbq_scalar = \$Foo::Barista::Bazoo::Qux::the_scalar or something like the Lexical::Alias module. Or for more oop-y applications aliased might be relevant.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

      Yes, in this case they're mine. However, in the general case, I want to:

      • use a module (which possibly has a Deeply::Nested::Package::Name),
      • not have any names dumped into my script's namespace (except the package I just used), and
      • be able to use the functions/variables in the module without having to type the Deeply::Nested::Package::Name every time.
      • Personally, I tend to prefer fully-qualifying names, otherwise I get confused where the name comes from.

Re: How can I use a module via a short name or alias?
by DrWhy (Chaplain) on Jan 17, 2011 at 18:03 UTC
    A little late to the party, but I just wanted to add my own solution which is to pull the important line out of Package::Alias and use it directly...
    *AliasPkg:: = \*Other::Long::Package::Name::I::Don't::Want::To::Deal:: +With:: ;
    You'll often need to put this in a BEGIN block, but YMMV.

    --DrWhy

    "If God had meant for us to think for ourselves he would have given us brains. Oh, wait..."