In Perl, how can I access a scalar defined in another package?
perl, perl-module
Solution
Even if `$exported_array` weren't lexically scoped in the `Example` package, `Example`'s `$exported_array` and main's `$exported_array` are two different things. The easiest way to change the example you've given is to 1. change `my` to `our` in the `Example` declaration and explicitly qualify the variable name.
our $exported_array;
...
print Dumper $Example::exported_array;
Otherwise, you need to make `Example` an `Exporter`. (Or just write an `Example::import` routine--but I' not going to cover that.)
package Example;
our $exported_array = ...;
our @EXPORT_OK = qw<$exported_array>;
use parent qw<Exporter>;
And in the script:
use Example qw<$exported_array>;
However, as you can actually export arrays (not just refs), I would make that:
our @exported_array = (...);
our @EXPORT_OK = qw<@exported_array>;
...
use Example qw<@exported_array>;
...
print Dumper( \@exported_array );
Problem
I seem to be stuck trying to access a scalar which is defined in another package, and have narrowed down an example to a simple test case where I can reproduce the issue. What I wish to be able to do it access a reference to a list which is in defined within the package 'Example', using the our mechanism, however, Dumper is showing that the variable is always undefined within example.pl: Example.pm looks like the following: ``` #!/usr/bin/perl -w use strict; use warnings; use diagnostics; package Example; use Data::Dumper; my $exported_array = [ 'one', 'two', 'three' ]; print Dumper $exported_array; 1; ``` And the code which uses this package looks like this: ``` #!/usr/bin/perl -w use strict; use warnings; use diagnostics; use Data::Dumper; use lib '.'; use Example; { package Example; use Data::Dumper; our $exported_array; print Dumper $exported_array; } exit 0; ``` Upon running this code, the first Dumper runs and things look normal, after this, the second Dumper, example.pl runs and the reference is then undefined: ``` $VAR1 = [ 'one', 'two', 'three' ]; $VAR1 = undef; ```