Perl files seem to combine namespaces without requiring

60 Views Asked by At

I have a perl file that uses a sub routine (a function) defined in a different module inside the same directory. However, that module is never required in the original file, nor is the subroutine defined anywhere in the file, nor is it called from the module properly.

From my understanding, a subroutine from a module is called like such

require "module1.pm";
Module1::greet();

However, the file im working with simply goes

greet()

How is this possible? Is it something to do with "import"? The file im working in is likely a module for a main file somewhere else that requires all the modules, does it work like that? If the subroutine's module is never specified, how do I track it down other than the comb through all the other modules in the directory? I didn't write the code i'm working with, so I'm not familiar with the structure.

1

There are 1 best solutions below

3
zdim On

There are many ways to provide functions to other code, and by the design of the whole system, which is quite flexible and fluid, some of them are quite devilous. (It is up to the developer's good practice and taste to choose.)

Consider this bad manner

main.pl

use warnings;
use strict;
use feature 'say';

use FindBin qw($RealBin);
use lib $RealBin;          # so we can load from the same directory

use Mod1;

say "In ", __PACKAGE__;

hey_mod2();  # *not* from Mod1

In the same directory, Mod1.pm

package Mod1;

use warnings;
use strict;
use feature 'say';

use Mod2;

1;

and Mod2.pm

package Mod2;

use warnings;
use strict;
use feature 'say';

# Write directly to main:: symbol table
# Just an example of what is possible -- please don't do this
*{main::hey_mod2} = \&greet;

sub greet {
    say "Uninvited hello from ", __PACKAGE__;
}

1;

When you run perl main.pl it prints

In main
Uninvited hello from Mod2

So yes, it is possible to push function names into programs even as they don't ask for nor know about it.

If you can provide more detail it may be possible to come up with a reasonable way to work with what you've got, but it is also possible that you may have to account for who calls who from where (etc) by going through files.