Reputation: 11266
I want to define some constants in one package and then use them in another package, but I don't seem to be doing this right! At first shot I was getting
Bareword "FAVORITE_COLOR" not allowed while "strict subs" in use at ...
I guess it was because I wasn't using the base path for my package in the lib() function,
Module My/Colors.pm
package My::Colors;
BEGIN {
use Exporter;
our($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
$VERSION = 1.00;
@ISA = qw(Exporter);
@EXPORT = qw( );
@EXPORT_OK = qw( FAVORITE_COLOR DISLIKED_COLOR );
%EXPORT_TAGS = ( 'all' => [ @EXPORT, @EXPORT_OK ], 'const' => [ 'FAVORITE_COLOR', 'DISLIKED_COLOR'] );
}
our @EXPORT_OK;
use lib qw( /home/dev );
use Carp;
use constant {
DISLIKED_COLOR => "green",
FAVORITE_COLOR => "red"
};
sub new {
my($class, %args) = @_;
my $self = bless({}, $class);
my $target = exists $args{target} ? $args{target} : "new";
$self->{target} = $target;
return $self;
}
1;
Module that includes exported constants color_driver.plx
#!/usr/bin/perl -w
use warnings;
use strict;
use diagnostics;
use lib qw( /home/dev/My );
use Colors;
use Colors qw(:const);
sub main{
my $color = new Colors;
print "Color is",FAVORITE_COLOR;
}
main();
any idea what I'm doing wrong?
When I remove strict the constant doesnt translate to its value =/
Updated Unfortunately now perl is complaining that it can't find new sub
Can't locate object method "new" via package "Colors" (perhaps you forgot to load "Colors"?) at color_driver.plx line 15 (#1)
Upvotes: 1
Views: 747
Reputation: 385496
In the module:
package My::Colors;
In the script:
use lib qw( /home/dev/My );
use Colors qw(:const);
my $color = new Colors;
Either change those lines of the module to
package Colors;
or change those lines of the script to
use lib qw( /home/dev );
use My::Colors qw(:const);
my $color = new My::Colors;
use Colors qw( :const );
is almost identical to
BEGIN {
require Colors;
Colors->import(qw( :const ));
}
You are telling Perl to look in the Colors
package/namespace for import
(and new
), but the module populates the package/namespace My::Colors
.
Upvotes: 3