Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading another packages symbol table in Perl

Tags:

perl

typeglob

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 ;
like image 871
justintime Avatar asked Nov 24 '25 15:11

justintime


2 Answers

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.

like image 177
Ether Avatar answered Nov 26 '25 16:11

Ether


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.

like image 29
FMc Avatar answered Nov 26 '25 18:11

FMc