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,
Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
In reply to Re: Wrap multiple programs
by Athanasius
in thread Wrap multiple programs
by jnarayan81
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |