in reply to Using an object's value instead of a global variable

The others have already pointed out why that's not a good idea. But to show it's still possible, I assume the following is close to what you want:
package Bar; use strict; use Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw(the_mascot); my $value = "camel"; my $data = \$value; sub the_mascot { print<<"END"; Hey, did you know that Perl's mascot is a: $$data END } sub new { my $class = shift; my $self = {}; $self->{ANIMAL} = $data; bless($self, $class); return $self; } sub animal { my $self = shift; ${$self->{ANIMAL}} = $_[0]; } sub mascot { the_mascot(); } 1;
Then in main script:
use strict; use Bar qw(the_mascot); my $a = new Bar; $a->animal("parrot"); $a->mascot; the_mascot(); $a->animal("firebird"); $a->mascot(); #output __END__ Hey, did you know that Perl's mascot is a: parrot Hey, did you know that Perl's mascot is a: parrot Hey, did you know that Perl's mascot is a: firebird
</code>

Replies are listed 'Best First'.
Re^2: Using an object's value instead of a global variable
by davido (Cardinal) on Jan 22, 2005 at 07:17 UTC

    What you have proven is that it's possible to declare a lexical at file-scope that works a lot like a package global (but not exactly), but without generating an entry in the package global symbol table. Thus, this file-scoped lexical is not available outside the package (ie, via some fully qualified name, nor outside the enclosing file).

    That doesn't show anyone how to cause an object's instance data to be available prior to object creation time, to a package bound sub (or a class method), which seems to be the question.


    Dave