tags:

views:

81

answers:

4

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  A: 

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.

FM
A: 

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

Benjamin Franz
Why the hate here? If you actually test my answer you will see it works.
Benjamin Franz
+4  A: 

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.

Ether
Can you modify this to asnwer the question - "the package name is in a string"
justintime
rephrase of previous comment - this way looks fine if the other package is known in advance but I cant see how to use it if the package name is specified at runtime.
justintime
+1  A: 

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.

brian d foy