nsg
nsg

Reputation: 539

how to export names when package name is different from file name?

I have a file Scanners.pm which contains 2 packages. I want both these packages to export some names. I do not want those packages be in separate files, I want them to be in one file.

When I write

package SCAN;

use Exporter;
our @ISA       = qw(Exporter);
our @EXPORT    = qw(@SCANNERS @NAMES %NAMES name_index process_scanners);
our @EXPORT_OK = qw();

and then in the calling .pl file

use Scanner;

the names in the @EXPORT list are not exported. How I do that?

Upvotes: 0

Views: 203

Answers (1)

Miller
Miller

Reputation: 35198

You can create a custom import sub for your Scanner package. Exporting Without Using Exporter's import Method.

Note, this code only will work if the user relies on the default @EXPORT only. If you want them to be able to specify what functions they want, then you'll have to filter before calling export_to_level.

package Scanner;

use Exporter;
our @ISA       = qw(Exporter);
our @EXPORT    = qw(scannersub);

use strict;
use warnings;

sub import {
    Scanner->export_to_level(1, @_);
    ScannerTwo->export_to_level(1, @_);
}

sub scannersub {
    print "scanner->sub says hi\n";
}


package ScannerTwo;

use Exporter;
our @ISA       = qw(Exporter);
our @EXPORT    = qw(scannertwosub);

sub scannertwosub {
    print "scannertwo->sub says hi\n";
}

1;

__END__

and your script

use Scanner;

use strict;
use warnings;

scannersub();
scannertwosub();

1;

__END__

Finally, I would be remis if I didn't mention that this isn't a great idea on it's surface. Future maintainers of this code will not easily be able to trace these subs. So whatever your reason for wanting them in the same file but different packages, I suspect there is a better solution.

Upvotes: 2

Related Questions