in reply to Using GetOpt::Std to parse switches with arguments

Yeah. This was a lil confusing for me to finally grasp too. One thing you should pay special attention to is that Getopt has two different methods (getopt and getopts) you can call and that you should know which one you want to use since they work a lil bit differently from each other depending on what you want to accomplish.

I generally use getopts with hash references since, to me, it is the easier way to do what I want. With that, I will show some of my own code:

use Getopt::Std; ... &parse_commandline; ... sub parse_commandline { my $funcName = (caller(0))[3]; print "\nWorking in function: $funcName\n" if $DEBUG; # c: require different config file (requires param) # q: quiet or cron mode # t: test mode (don't do anything. Just run through the motions) # v: verbose mode (same as debug) # V: version information. # d: debug mode (extra output) # h: help getopts('c:qtrvVdh',\%ARGS); ## <- here is the hash ref! # From there I just check the hash{switch} # to see if what I want is there and set # script environment accordingly. $DEBUG = 1 if ( exists $ARGS{'v'} ); $DEBUG = 1 if ( exists $ARGS{'d'} ); $NO_RULE_OUTPUT = 1 if ( exists $ARGS{'r'} ); &version if ( exists $ARGS{V} ); &funcUsage if ( exists $ARGS{h} ); if ( defined $ARGS{'c'} ) { if ( ! &check_for_valid_conf($ARGS{'c'}) ) { print "\n$config_file: Invalid config file specified on ". "command line\n"; &funcUsage } else { $config_file = $ARGS{'c'}; } } $CRON_MODE = 1 if ( exists $ARGS{'q'} ); $TEST_MODE = 1 if ( exists $ARGS{'t'} and !$CRON_MODE ); }
There are a lot of ways to do it cleaner and nicer. The drawback to mine is that I have to pay attention to what I am doing when I see a variable I want to do something with and make sure that I don't *do* something prior to my knowing every variable. For example, setting debug mode *after* running some subs from other switches when what I wanted to do was set debug prior to running anything else. If you will notice, I have my DEBUG set before anything else (or at least its one of the first).

So, in a nutshell, the way I do it (and by all means mine is not the best way but its a way...as is the way with Perl), using getopts('switches I want',\%HASHREF); is my favorite. Note that in 'switches I want' you will see letters followed by ':'. That ':' specifies that that the 'i' parameter in getopts('hi:o:',\%HASHREF) needs an argument on the command line, ie myscript.pl -i input_file ... and my '-o' will need one too. However, '-h' will not. Also note, that this is easy if you want optional variables because when you are testing for defined'ness or existence of your hashed arguments, you simply ignore doing anything with those that are not defined or in existence.

I hope this helps.

_ _ _ _ _ _ _ _ _ _
- Jim
Insert clever comment here...