I am trying to read a global symbol from another package. I have the package name as a string.
I am using qualify_to_ref from Symbol module
my $ref = qualify_to_ref ( 'myarray', 'Mypackage' ) ;
my @array = @$ref ;
gives me Not an ARRAY reference at ...... I presume I am getting the format of the dereference wrong.
Here is a complete example program.
use strict;
use Symbol ;
package Mypackage ;
our @myarray = qw/a b/ ;
package main ;
my $ref = qualify_to_ref ( 'myarray', 'Mypackage' ) ;
my @array = @$ref ;
You can also do this without using an external module, as discussed in perldoc perlmod under "Symbol Tables":
package Mypackage;
use strict;
use warnings;
our @myarray = qw/a b/;
package main;
our @array;
*array = \@Mypackage::myarray;
print "array from Mypackage is @array\n";
However, whether this is a good idea depends on the context of your program. Generally it would be a better idea to use an accessor method to get at Mypackage's values, or export the variable to your namespace with Exporter.
The qualify_to_ref function returns a typeglob reference, which you can de-reference like this:
my @array = @{*$ref};
The typeglob dereferencing syntax is documented here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With