|Think about Loose Coupling|
Modules as executable scripts?by graff (Chancellor)
|on Jun 15, 2007 at 01:24 UTC||Need Help??|
graff has asked for the
wisdom of the Perl Monks concerning the following question:
Every now and then, I'd like to implement something as a module, but also have it available as an executable script -- for example, I might want to "anonymize" zip codes in some way, keeping each zip code distinct (so I can
This flexibility is a common feature in Python -- you just add a few lines of code at the end of a "module" script to say, in effect, "if this file is being executed from the command line, invoke the class and/or object functions as follows, using the command-line args like so..."
So, if Python can do it, surely Perl can too, right? And so my question is: what would be a good way to do this?
My module-building skills don't get a lot of exercise, and I wouldn't presume to think I have a clue, but I came up with an example that seems to work, in a very simple-minded, unsophisticated way. Here's a little file I call "Runnable.pm":
I can "chmod +x" that file, run it with command-line args, and it prints "did something with ...(those args)". Now, here's a script that uses Runnable.pm as a module:
Sure enough, that runs too, and it prints exactly what I was hoping to see. The only "extra details" I need to handle here are to make sure that Runnable.pm is in my shell's execution PATH, and to also make sure that its location shows up in @INC whenever I use it in another script.
Having the ".pm" extension on the command line when I run the module as a program seems a bit klunky and odd, but I guess there's no way around that if I want to use the same file as a module in other scripts in the "normal" way.
Does anyone see a problem with this, or a better way?