jacques has asked for the wisdom of the Perl Monks concerning the following question:
THE BACKGROUND
I am writing a module with a funtional and OO interface a la CGI.pm. There is one function that is exported by request. This function prints data to STDOUT. For example,
There are 2 methods, animal and mascot. Like the exported function, the method called mascot also prints to STDOUT. Here's another example:use Some::Module qw(the-mascot); the-mascot();
Now keeping all of this in mind let me show you some codeuse Some::Module; my $a = new Some::Module; $a->animal("parrot"); $a->mascot;
THE CODE
This is my code. I know that it does not work. The purpose of this code will become apparent in my question. This is pseudo code. So if you see a typo or don't see strict or warnings, please don't freak out.
$data = "camel"; 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(); }
THE QUESTION
Notice that I have a global variable called $data. This variable has 2 purposes. First, $data is used in the heredoc in the the-mascot function. Second, $data is the default value for $self->{ANIMAL} in the new subroutine. I want to eliminate the use of this global variable.
Instead of using $data in the heredoc, I want to use the current value of $self->{ANIMAL}. Remember that this value gets set in the new subroutine. But it SHOULD change if the user calls the animal method in the main package, as I did in the previous example. So when someone says $a->animal("parrot"), then $a->mascot should print:
Hey, did you know that Perl's mascot is a: parrot
Now before you reply, remember that this would not work:
This doesn't work. Remember that the-mascot is a function exported by request. It is not a method! So I would like to set the value for $self->{ANIMAL} in the new subroutine and then reference that value in other subroutines which are not methods and do not care if the constructor is ever used in main.sub the-mascot { my $self = shift; print <<"END"; Hey, did you know that Perl's mascot is a: $self->{ANIMAL} END }
How could I accomplish this and eliminate the use of the global variable? Thanks.
|
|---|