in reply to Re^2: Passing Parameters to subroutine
in thread Passing Parameters to subroutine
Here is one possible implementation:
How to get GetOpts to parse say: command --test 23 --fancyprint is more complicated than the above syntax, but certainly possible.use strict; use warnings; use Getopt::Long; my $demo = 0; # default value (false) my $test = 0; # default value (false) GetOptions ('demo' => \$demo, 'test' => \$test); ### Once command line is parsed using GetOpts, THEN execute code ### based upon the flags which are set. ### GetOpts removes what it knows about from @ARGV - if there is ### anything left, then you have a syntax error. ### It is up to you to check for contradictory options, like ### perhaps asking for --demo and --test at the same time! if (@ARGV) { print "Illegal syntax \'@ARGV\' is bogus!\n"; printHelp(); } if (!($demo or $test)) { print "No option specified!\n"; printHelp(); } if (!($demo xor $test)) #test for inconsistent options { print "Only one option allowed!\n"; printHelp(); } sub printHelp { print "*** print something useful for help message**\n"; exit (1); #error exit to shell - the command "didn't work" } ### actual "code" is here ### demo() if $demo; #simple for this scenario test() if $test; sub demo { print "doing a demo\n"; } sub test { print "doing a test\n"; } __END__ example runs: >perl longopts.pl No option specified! *** print something useful for help message** >perl longopts.pl -d abc Illegal syntax 'abc' is bogus! *** print something useful for help message** >perl longopts.pl -d -t Only one option allowed! *** print something useful for help message** >perl longopts.pl adf Illegal syntax 'adf' is bogus! *** print something useful for help message** >perl longopts.pl -d doing a demo >perl longopts.pl -t doing a test
|
|---|