Search code examples
perlnamespacespackagesubroutine

How can I call a subroutine declared in another package without prefixing the subroutine name with its package name?


I'm not entirely sure this is possible, but I would like to simply shorten the name of the subroutine I'm calling declared in another package by just omitting the package name.

For example, I have a module defined:

package Package1;

use strict;
use warnings;

BEGIN 
{
  require Exporter;
  our @ISA = qw( Exporter );
  our @EXPORT_OK = qw( subroutine1 );
}

sub subroutine1
{
  print "Hello!$/";
}

return 1;

And I have a driver application defined:

use strict;
use warnings;

use Package1;

&Package1::subroutine1;

The only way I can seem to shorten the call to subroutine1 is with making an alias like the following:

*s1 = \&Package1::subroutine1;
&s1;

Surely I'm being a doofus and missing something here.. Is there a cleaner way to achieve this?


Solution

  • Change

    use Package1;
    

    to

    use Package1 qw( subroutine1 );
    

    or change

    our @EXPORT_OK = qw( subroutine1 );
    

    to

    our @EXPORT = qw( subroutine1 );
    

    I recommend the first change.