Reading another packages symbol table in Perl

650 Views Asked by At

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 ;
4

There are 4 best solutions below

0
On BEST ANSWER

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.

1
On

You need to dereference it: @$$ref instead of @$ref

2
On

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.

0
On

Beside the way that FM has already noted, you can access particular parts of a typeglob through it's hash-like interface:

my $array =  *{$ref}{ARRAY};

This can be handy to get to the parts, such as the IO portions, that don't have a sigil. I have a chapter about this sort of stuff in Mastering Perl.