[Melbourne-pm] module importing
Mathew Robertson
mathew.robertson at netratings.com.au
Tue May 22 23:46:18 PDT 2007
put this in MyModule.pm:
package MyModule;
use strict;
use warnings;
our $database;
sub import {
my $class = shift;
for (my $i=0; $i< $#_; $i+=2) {
if ($_[$i] eq "database") {
$database = $_[$i+1];
}
}
if ($database) {
print "Using database: $database $/";
}
return $class;
}
sub do_something {
print "do_something(".join(",", at _)." with database $database $/";
}
sub DESTROY {
if ($database) {
print "Disconnecting database: $database $/";
}
}
1;
Now this in test.pl
#!/usr/bin/perl
use strict;
use warnings;
use MyModule database => "fred";
print "main $/";
MyModule::do_something("SELECTING...");
now:
set PERL5LIB="$PERL5LIB:."
chmod +x test.pl
./test.pl
So.... basically create a sub called "import" - the first argument is
the package/class name. The rest of the arguments are whatever you
supply as arguments to the 'use'. Parse the args and store your value
in an 'our' variable.
This help?
Mathew Robertson
Josh Heumann wrote:
> Hi, all. After some confusing book- and soul-searching, I come to the
> group with a question. I want to do something like this:
>
> use MyModule env => test;
>
> to tell the module that is being used that it should use the test
> database. What do I need to do to capture that in MyModule?
>
> For extra credit, what if I want to use that information in something
> in MyModule that happens in a statement that isn't in a subroutine?
>
> All of my tests seem to indicate that I'm out of luck because the
> statement outside of a subroutine gets executed at compile time, while
> the use statement gets run at runtime. I feel like I could cobble
> something together, but it would be a hack and just plain wrong.
>
> Thanks for your help.
>
> Josh
> _______________________________________________
> Melbourne-pm mailing list
> Melbourne-pm at pm.org
> http://mail.pm.org/mailman/listinfo/melbourne-pm
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.pm.org/pipermail/melbourne-pm/attachments/20070523/a64ded77/attachment.html
More information about the Melbourne-pm
mailing list