Hello jnarayan81,
We can solve any problem by introducing an extra level of indirection. — the fundamental theorem of software engineering
You can achieve your stated goal by adding a suitable command-line option and refactoring accordingly:
use strict;
use warnings;
use Getopt::Long;
my $function;
my $data = 'file1';
my $length = 4;
my $width = 5;
my $verbose;
die "$0: Argument required.\n" unless @ARGV;
GetOptions
(
'function=s' => \$function,
'length=i' => \$length,
'width=i' => \$width,
'file=s' => \$data,
verbose => \$verbose,
) or die "Error in command line arguments\n";
if ($function eq 'plot')
{
my $fh = read_fh($data);
print "$_\n" while <$fh>;
}
elsif ($function eq 'calc')
{
my $total = $width * $length;
print $total;
}
else
{
die "Unsupported function\n";
}
sub read_fh # Open and Read a file
{
my $filename = shift @_;
my $filehandle;
if ($filename =~ /gz$/)
{
open $filehandle, "gunzip -dc $filename |" or die $!;
}
else
{
open $filehandle, "<$filename" or die $!;
}
return $filehandle;
}
But, really, this is a bad idea. It won’t scale well, and in any case, what does it gain? It’s actually easier for a user to enter:
perl calc.pl --length 20 --width 30
than
perl main.pl --function calc --length 20 --width 30
and by keeping the scripts separate, you avoid the complications that arise from having overlapping options. (For example, what if you want the --length option to default to 10 when plotting but to 20 when calculating? Then you would need to have separate options:
...
my $plotlength = 10;
my $calclength = 20;
...
GetOptions
(
...
'plotlength=i' => \$plotlength,
'calclength=i' => \$calclength,
...
) or die "Error in command line arguments\n";
This could get messy very quickly.)
So, it’s best to follow stevieb’s advice and modularise your code as much as possible.
Hope that helps,
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.