Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I export a package symbol to a namespace in Perl?

I'm having trouble understanding how to export a package symbol to a namespace. I've followed the documentation almost identically, but it seems to not know about any of the exporting symbols.

mod.pm

#!/usr/bin/perl

package mod;

use strict;
use warnings;

require Exporter;

@ISA = qw(Exporter);
@EXPORT=qw($a);


our $a=(1);

1;

test.pl

$ cat test.pl
#!/usr/bin/perl

use mod;

print($a);

This is the result of running it

$ ./test.pl
Global symbol "@ISA" requires explicit package name at mod.pm line 10.
Global symbol "@EXPORT" requires explicit package name at mod.pm line 11.
Compilation failed in require at ./test.pl line 3.
BEGIN failed--compilation aborted at ./test.pl line 3.

$ perl -version
This is perl, v5.8.4 built for sun4-solaris-64int
like image 364
Mike Avatar asked May 26 '10 13:05

Mike


3 Answers

Try this:

package mod;                # Package name same as module.

use strict;
use warnings;

use base qw(Exporter);

our @ISA    = qw(Exporter); # Use our.
our @EXPORT = qw($z);       # Use our. Also $a is a bad variable name
                            # because of its special role for sort().

our $z = 1;

1;
like image 181
FMc Avatar answered Dec 11 '22 07:12

FMc


It's not telling you that you're having a problem exporting $a. It's telling you that you're having a problem declaring @ISA and @EXPORT. @ISA and @EXPORT are package variables and under strict, they need to be declared with the our keyword (or imported from other modules--but that is not likely with those two). They are semantically different--but not functionally different--from $a.

Nanny NOTE: @EXPORT is not considered polite. Through Exporter it dumps its symbols in the using package. Chances are if you think something is good to export--and it is--then it will be worth it for the user to request it. Use @EXPORT_OK instead.

like image 21
Axeman Avatar answered Dec 11 '22 07:12

Axeman


Others have correctly identified the problem and offered solutions. I thought it would be useful to point out a debugging tip. To isolate a problem to a given file, you can attempt to compile just that file using perl -c(refer to perlrun):

perl -c mod.pm

This would have given you the same error message, leading you to realize the problem is in your .pm file, not your .pl file.

like image 44
toolic Avatar answered Dec 11 '22 08:12

toolic