How to get module to execute as standalone.

B

billy

I've seen it somewhere but cannot recall.
I have a module that I call from several difference files. call it
x.pl
I need to have this module also be an executable. The part I've seen
is that there
is an eval in the file that takes the command line arguments and passes
them to the
subroutine.

????

package x;
....

`eval $0 "use x; x(@ARGV);`

I know it can be done, just not sure how.
 
A

Anno Siegel

billy said:
I've seen it somewhere but cannot recall.
I have a module that I call from several difference files. call it
x.pl

What's a "difference file"? Or do you mean "several different files"?
I need to have this module also be an executable. The part I've seen
is that there
is an eval in the file

Which file?
that takes the command line arguments and passes
them to the
subroutine.

????

package x;
...

`eval $0 "use x; x(@ARGV);`

I know it can be done, just not sure how.

I'm not sure what eval() is supposed to buy you here.

If you want a Perl module (a .pm file) to be runnable as a plain script,
put the script code under a condition that skips it if caller() is defined.
It will only run if the file is *not* loaded as a module.

For example, put this in x.pm:


#!/usr/bin/perl
use strict; use warnings; $| = 1; # @^~`

if ( !defined caller ) {
print "Running as a script\n";
x::func();
}

############################################################

package x;

# Exporter boilerplate goes here

sub func {
print "func() called\n";
}

1;


This file can be used as a module:

perl -Mx -e'x::func()'

and as a stand-alone script:

perl x.pm

Anno
 
B

brian d foy

billy said:
I've seen it somewhere but cannot recall.
I have a module that I call from several difference files. call it
x.pl
I need to have this module also be an executable.

I talk about modules as scripts (which I called 'modulinos") in a
Perlmonks post: http://www.perlmonks.org/index.pl?node_id=396759

And also in an article for The Perl Journal:
http://www.tpj.com/documents/s=9621/tpj0411e/0411e.html

You may have seen this stuff before in the diagnostics.pm module.

Good luck.
*** Free account sponsored by SecureIX.com ***
*** Encrypt your Internet usage with a free VPN account from http://www.SecureIX.com ***
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top