In this earlier Stackoverflow question and especially brian d foy’s “How a Script Becomes a Module” I’ve read about how to set up code so that it can be run as either a script or a module, using this technique:
package SomeModule;
__PACKAGE__->run(@ARGV) unless caller();
sub run {
# Do stuff here if you are running the file as
# a script rather than a module.
}
What is the purpose of __PACKAGE__ in this setup? Why not just do this?
run(@ARGV) unless caller();
If you say
__PACKAGE__->run(@ARGV)thenruncan be defined in a class you inherit from or allows a class to inherit from this one. If you just sayrun(@ARGV)you are missing the class information. This only matters if you are doing OO style programming.Put the following in a file named
Foo.pm, and then sayperl Foo.pm 1 2 3Now put the following in
Bar.pm, and sayperl Bar.pm a b c.Now lets see what happens if you don’t use
__PACKAGE__in this environment. Make the first section of code inFoo.pmlook like this:Now run
perl Foo.pm 1 2 3. Everything should still look right. Now try runningperl Bar.pm a b c. We still get output, but it is not the output we expect. What happens if we remove__PACKAGE__fromBar.pm? Well, we get and error:Undefined subroutine &Bar::main called at Bar.pm line 8.This is because there is nomainfunction in the module and we are not calling it with the class, so it won’t look for it in the
Foopackage anymore.