开发者

Reading another packages symbol table in Perl

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 开发者_Go百科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 ;


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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜