in reply to Re: Passing Parameters to subroutine
in thread Passing Parameters to subroutine

Resolved
GetOptions( 'demo' => sub{demo();}, 'test' => sub{test();} ) or die("Error in command line arguments\n");

Replies are listed 'Best First'.
Re^3: Passing Parameters to subroutine
by Marshall (Canon) on Mar 21, 2022 at 10:41 UTC
    I don't think that you understood what the Monks are saying. This is not "resolved". Do not use GetOpts in this way because amongst other things, you do not get proper checking of the input command line for errors. The entire command line should be checked for errors before you do anything. Calling a sub by GetOpts is part of command line checking and you don't need that to do what you want to do - or my understanding of what you want to do.

    Here is one possible implementation:

    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
    How to get GetOpts to parse say: command --test 23 --fancyprint is more complicated than the above syntax, but certainly possible.