Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Starting a subroutine from the command line 1

Status
Not open for further replies.

Ramnarayan

Programmer
Jan 15, 2003
56
US
I am trying to modify all the scripts to work in a way that from the command line, I should be able to call a subroutine in the perl script to be executed without having to pass through all the sub routines in the program. For example,

abc.pl
======
&create_pdfs;
&create_gifs;
&create_pdf_inv;
&create_gif_inv;

sub create_pdfs(){...}
sub create_gifs(){...}
sub create_pdf_inv(){...}
sub create_gif_inv(){...}

Now what I want to do is that from the command line, when I execute abc.pl, I should be able to execute only the subroutine create_pdfs() only and the other subroutines should never be executed.

Can someone tell me how to pass the subroutines to a command line?

Thanks for your support and time.


 
You could get the subroutine name from the command line then use switch case statements to run the appropriate subroutine.
 
Thanks TomThumbKP for the answer. But I am unable to understand what you are saying. Can you explain a little bit using some examples.

Did you mean that I have to pass the subroutines as a arguements to the command line? If so, please tell me how I can do that?
 
If this is your script:

Code:
switch ($ARGV[0]){
    case "foo"  { foo(); }
    case "bar"  { bar(); }
    else        { print "I don't know what you want\n";}
}

sub foo(){
    print "foo\n";
}
sub bar(){
    print "bar\n";
}

Then call it like this:

Code:
perl foobar.pl foo

and it will run only the foo subroutine. A few caveats. I am at work and do not have access to perl right now so this is untested. This is the bare minimum implementation. There is no error handling in it at all.
 
Thanks tom. It is really help ful. So all i have to do is modify the scripts to have nested cases and call them in the command line.

Not much of a rework. Thanks a ton!
 
Have a look at Getopt::Long for how to control commandline arguments.

BTW switch only available if you use Switch.pm. In a regular script you'll need to have something like:
Code:
my %opts;
GetOptions (\%opts, 'pdf', 'gif', 'ipdf', 'igif');
&create_pdfs	if($opts{pdf});
&create_gifs	if($opts{gif};
&create_pdf_inv	if($opts{ipdf};
&create_gif_inv	if($opts{igif};
You then pass the arguments as:
Code:
perl abc.pl -pdf -gif -ipdf -igif
Omit the appropriate arguments when you don't want those subroutines to run.

Barbie
Leader of Birmingham Perl Mongers
 
This switch.pm is perfect. I always hated perl for not having it, the only thing I could found perl lacking.

Thanx misbarbell!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top