opensourcer has asked for the wisdom of the Perl Monks concerning the following question:

i have a module
############## Manager.pm ######### package Manager; use Exporter; @ISA = qw(Exporter); @EXPORT = qw ($var); my $var; sub new { my $caller = shift; my $class = ref($caller); my $self = bless {}, $class; return $self; } sub import { print "Hello world\n"; $var ="PerlHacks"; } 1;
and im trying to accress $var by using the "use Manager.pm"
use Manager; my $Mref = Manager::new(); ## i don't want to use $Manager::var ## im looking for other ways of accessing $var. ## doesn't print anything. print $Mref::$var;

Replies are listed 'Best First'.
Re: accessing module variables howto
by davido (Cardinal) on Aug 29, 2006 at 07:07 UTC

    Exporter implements an import() routine. You're overriding it by declaring your own "sub import {...." Since your own version of import() doesn't do what is necessary to import the variable into package main's namespace, you're unable to use $var unless you use the fully qualified name.


    Dave

Re: accessing module variables howto
by jaa (Friar) on Aug 29, 2006 at 07:32 UTC
    Lots of things wrong with your sample code - but probably the most crucial, is that it contains a number of basic syntax problems, and so would never have actually run.

    Perhaps you want something like:

    use strict; # Note how a constructor is called # Classname->new() NOT Classname::new() my $Mref = Manager->new(); # Prints the value of var for $Mref using an accessor method print $M1->var, "\n"; print $M1->var("peaches"), "\n"; # Each instance has its own var my $M2 = Manager->new(); $M2->var("apples"); ############## Manager.pm ######### package Manager; use strict; # reworked constructor sub new { my $class = shift; # first arg is name of class # create anon hash containing member var # and bless into class... my $self = bless { var => "var initialised", }, $class; return $self; } # return true for successful package initialisation 1; # set/get accessor for var - sub var { my $self = shift; $self->{var} = $_[0] if scalar @_; return $self->{var}; }
    There are many ways to use object orientation, this is just one of them...
Re: accessing module variables howto
by shmem (Chancellor) on Aug 29, 2006 at 08:08 UTC
    Apart from the other posts -- do this:
    my $Mref = Manager::new(); # ... print $Manager::var;
    $Mref is an object, but $var is not bound to an object, but a package variable. So you have to qualify it with the package namespace identifier Manager:: to access it.

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}